main.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package main
  2. import (
  3. "bytes"
  4. "net/http"
  5. _ "net/http/pprof"
  6. "os"
  7. "path"
  8. "runtime"
  9. "strings"
  10. "encoding/json"
  11. dto "github.com/prometheus/client_model/go"
  12. "github.com/coroot/coroot-node-agent/common"
  13. "github.com/coroot/coroot-node-agent/containers"
  14. "github.com/coroot/coroot-node-agent/flags"
  15. "github.com/coroot/coroot-node-agent/logs"
  16. "github.com/coroot/coroot-node-agent/node"
  17. "github.com/coroot/coroot-node-agent/profiling"
  18. "github.com/coroot/coroot-node-agent/prom"
  19. "github.com/coroot/coroot-node-agent/tracing"
  20. "github.com/prometheus/client_golang/prometheus"
  21. "github.com/prometheus/client_golang/prometheus/promhttp"
  22. "golang.org/x/mod/semver"
  23. "golang.org/x/sys/unix"
  24. "golang.org/x/time/rate"
  25. "k8s.io/klog/v2"
  26. )
  27. var (
  28. version = "unknown"
  29. )
  30. const minSupportedKernelVersion = "4.16"
  31. func uname() (string, string, error) {
  32. runtime.LockOSThread()
  33. defer runtime.UnlockOSThread()
  34. f, err := os.Open("/proc/1/ns/uts")
  35. if err != nil {
  36. return "", "", err
  37. }
  38. defer f.Close()
  39. self, err := os.Open("/proc/self/ns/uts")
  40. if err != nil {
  41. return "", "", err
  42. }
  43. defer self.Close()
  44. defer func() {
  45. unix.Setns(int(self.Fd()), unix.CLONE_NEWUTS)
  46. }()
  47. err = unix.Setns(int(f.Fd()), unix.CLONE_NEWUTS)
  48. if err != nil {
  49. return "", "", err
  50. }
  51. var utsname unix.Utsname
  52. if err := unix.Uname(&utsname); err != nil {
  53. return "", "", err
  54. }
  55. hostname := string(bytes.Split(utsname.Nodename[:], []byte{0})[0])
  56. kernelVersion := string(bytes.Split(utsname.Release[:], []byte{0})[0])
  57. return hostname, kernelVersion, nil
  58. }
  59. func machineID() string {
  60. for _, p := range []string{"sys/devices/virtual/dmi/id/product_uuid", "etc/machine-id", "var/lib/dbus/machine-id"} {
  61. payload, err := os.ReadFile(path.Join("/proc/1/root", p))
  62. if err != nil {
  63. klog.Warningln("failed to read machine-id:", err)
  64. continue
  65. }
  66. id := strings.TrimSpace(strings.Replace(string(payload), "-", "", -1))
  67. klog.Infoln("machine-id: ", id)
  68. return id
  69. }
  70. return ""
  71. }
  72. func whitelistNodeExternalNetworks() {
  73. netdevs, err := node.NetDevices()
  74. if err != nil {
  75. klog.Warningln("failed to get network interfaces:", err)
  76. return
  77. }
  78. for _, iface := range netdevs {
  79. for _, p := range iface.IPPrefixes {
  80. if p.IP().IsLoopback() || common.IsIpPrivate(p.IP()) {
  81. continue
  82. }
  83. // if the node has an external network IP, whitelist that network
  84. common.ConnectionFilter.WhitelistPrefix(p)
  85. }
  86. }
  87. }
  88. type MetricItemData struct {
  89. Label map[string]string `json:"metric_tags"`
  90. Value any `json:"value"`
  91. }
  92. type MetricData struct {
  93. MetricKey string `json:"metric_key"`
  94. Metric []MetricItemData `json:"metric"`
  95. }
  96. func main() {
  97. klog.LogToStderr(false)
  98. klog.SetOutput(&RateLimitedLogOutput{limiter: rate.NewLimiter(rate.Limit(*flags.LogPerSecond), *flags.LogBurst)})
  99. klog.Infoln("agent version:", version)
  100. hostname, kv, err := uname()
  101. if err != nil {
  102. klog.Exitln("failed to get uname:", err)
  103. }
  104. klog.Infoln("hostname:", hostname)
  105. klog.Infoln("kernel version:", kv)
  106. ver := common.KernelMajorMinor(kv)
  107. if ver == "" {
  108. klog.Exitln("invalid kernel version:", kv)
  109. }
  110. if semver.Compare("v"+ver, "v"+minSupportedKernelVersion) == -1 {
  111. klog.Exitf("the minimum Linux kernel version required is %s or later", minSupportedKernelVersion)
  112. }
  113. whitelistNodeExternalNetworks()
  114. machineId := machineID()
  115. tracing.Init(machineId, hostname, version)
  116. logs.Init(machineId, hostname, version)
  117. registry := prometheus.NewRegistry()
  118. registerer := prometheus.WrapRegistererWith(prometheus.Labels{"machine_id": machineId}, registry)
  119. registerer.MustRegister(info("node_agent_info", version))
  120. if err := registerer.Register(node.NewCollector(hostname, kv)); err != nil {
  121. klog.Exitln(err)
  122. }
  123. processInfoCh := profiling.Init(machineId, hostname)
  124. cr, err := containers.NewRegistry(registerer, kv, processInfoCh)
  125. if err != nil {
  126. klog.Exitln(err)
  127. }
  128. defer cr.Close()
  129. profiling.Start()
  130. defer profiling.Stop()
  131. // 创建一个/metrics路由处理函数
  132. metricsHandler := func(w http.ResponseWriter, r *http.Request) {
  133. // 从注册表中获取指标数据
  134. metrics, err := registry.Gather()
  135. if err != nil {
  136. // 错误处理
  137. http.Error(w, err.Error(), http.StatusInternalServerError)
  138. return
  139. }
  140. var Data []MetricData
  141. for _, metric := range metrics {
  142. if metric.GetName() != "container_net_tcp_successful_connects_total" &&
  143. metric.GetName() != "container_net_tcp_failed_connects_total" &&
  144. metric.GetName() != "container_net_tcp_retransmits_total" &&
  145. metric.GetName() != "container_net_tcp_listen_info" &&
  146. metric.GetName() != "container_http_requests_total" &&
  147. metric.GetName() != "container_http_requests_duration_seconds_total" &&
  148. metric.GetName() != "container_application_type" {
  149. continue
  150. }
  151. var item MetricData
  152. var itemOther MetricData
  153. item.MetricKey = metric.GetName()
  154. for _, m := range metric.GetMetric() {
  155. metricItem := MetricItemData{}
  156. label := make(map[string]string)
  157. for _, l := range m.GetLabel() {
  158. label[l.GetName()] = l.GetValue()
  159. }
  160. metricItem.Label = label
  161. switch metric.GetType() {
  162. case dto.MetricType_COUNTER:
  163. metricItem.Value = m.GetCounter().GetValue()
  164. item.Metric = append(item.Metric, metricItem)
  165. case dto.MetricType_GAUGE:
  166. metricItem.Value = m.GetGauge().GetValue()
  167. item.Metric = append(item.Metric, metricItem)
  168. case dto.MetricType_HISTOGRAM:
  169. item.MetricKey = metric.GetName() + "_sum"
  170. metricItem.Value = m.GetHistogram().GetSampleSum()
  171. item.Metric = append(item.Metric, metricItem)
  172. metricItemOther := MetricItemData{}
  173. metricItemOther.Label = label
  174. itemOther.MetricKey = metric.GetName() + "_count"
  175. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  176. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  177. default:
  178. continue
  179. }
  180. }
  181. Data = append(Data, item)
  182. if metric.GetType() == dto.MetricType_HISTOGRAM {
  183. Data = append(Data, itemOther)
  184. }
  185. }
  186. // 将指标数据转换为JSON格式
  187. jsonData, err := json.Marshal(Data)
  188. //jsonData, err := json.Marshal(metrics)
  189. if err != nil {
  190. http.Error(w, err.Error(), http.StatusInternalServerError)
  191. return
  192. }
  193. w.Header().Set("Content-Type", "application/json")
  194. w.Write(jsonData)
  195. }
  196. if err := prom.StartAgent(machineId); err != nil {
  197. klog.Exitln(err)
  198. }
  199. http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: logger{}, Registry: registerer}))
  200. http.HandleFunc("/metrics2", metricsHandler)
  201. klog.Infoln("listening on:", *flags.ListenAddress)
  202. klog.Errorln(http.ListenAndServe(*flags.ListenAddress, nil))
  203. }
  204. func info(name, version string) prometheus.Collector {
  205. g := prometheus.NewGauge(prometheus.GaugeOpts{
  206. Name: name,
  207. ConstLabels: prometheus.Labels{"version": version},
  208. })
  209. g.Set(1)
  210. return g
  211. }
  212. type logger struct{}
  213. func (l logger) Println(v ...interface{}) {
  214. klog.Errorln(v...)
  215. }
  216. type RateLimitedLogOutput struct {
  217. limiter *rate.Limiter
  218. }
  219. func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
  220. if !o.limiter.Allow() {
  221. return len(data), nil
  222. }
  223. return os.Stderr.Write(data)
  224. }