main.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  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/prom"
  18. "github.com/coroot/coroot-node-agent/tracing"
  19. "github.com/prometheus/client_golang/prometheus"
  20. "github.com/prometheus/client_golang/prometheus/promhttp"
  21. "golang.org/x/mod/semver"
  22. "golang.org/x/sys/unix"
  23. "golang.org/x/time/rate"
  24. "k8s.io/klog/v2"
  25. )
  26. var (
  27. version = "unknown"
  28. )
  29. const minSupportedKernelVersion = "4.16"
  30. func uname() (string, string, error) {
  31. runtime.LockOSThread()
  32. defer runtime.UnlockOSThread()
  33. f, err := os.Open("/proc/1/ns/uts")
  34. if err != nil {
  35. return "", "", err
  36. }
  37. defer f.Close()
  38. self, err := os.Open("/proc/self/ns/uts")
  39. if err != nil {
  40. return "", "", err
  41. }
  42. defer self.Close()
  43. defer func() {
  44. unix.Setns(int(self.Fd()), unix.CLONE_NEWUTS)
  45. }()
  46. err = unix.Setns(int(f.Fd()), unix.CLONE_NEWUTS)
  47. if err != nil {
  48. return "", "", err
  49. }
  50. var utsname unix.Utsname
  51. if err := unix.Uname(&utsname); err != nil {
  52. return "", "", err
  53. }
  54. hostname := string(bytes.Split(utsname.Nodename[:], []byte{0})[0])
  55. kernelVersion := string(bytes.Split(utsname.Release[:], []byte{0})[0])
  56. return hostname, kernelVersion, nil
  57. }
  58. func machineID() string {
  59. for _, p := range []string{"sys/devices/virtual/dmi/id/product_uuid", "etc/machine-id", "var/lib/dbus/machine-id"} {
  60. payload, err := os.ReadFile(path.Join("/proc/1/root", p))
  61. if err != nil {
  62. klog.Warningln("failed to read machine-id:", err)
  63. continue
  64. }
  65. id := strings.TrimSpace(strings.Replace(string(payload), "-", "", -1))
  66. klog.Infoln("machine-id: ", id)
  67. return id
  68. }
  69. return ""
  70. }
  71. func whitelistNodeExternalNetworks() {
  72. netdevs, err := node.NetDevices()
  73. if err != nil {
  74. klog.Warningln("failed to get network interfaces:", err)
  75. return
  76. }
  77. for _, iface := range netdevs {
  78. for _, p := range iface.IPPrefixes {
  79. if p.IP().IsLoopback() || common.IsIpPrivate(p.IP()) {
  80. continue
  81. }
  82. // if the node has an external network IP, whitelist that network
  83. common.ConnectionFilter.WhitelistPrefix(p)
  84. }
  85. }
  86. }
  87. type MetricItemData struct {
  88. Label map[string]string `json:"metric_tags"`
  89. Value any `json:"value"`
  90. }
  91. type MetricData struct {
  92. MetricKey string `json:"metric_key"`
  93. Metric []MetricItemData `json:"metric"`
  94. }
  95. func main() {
  96. klog.LogToStderr(false)
  97. klog.SetOutput(&RateLimitedLogOutput{limiter: rate.NewLimiter(rate.Limit(*flags.LogPerSecond), *flags.LogBurst)})
  98. klog.Infoln("agent version:", version)
  99. hostname, kv, err := uname()
  100. if err != nil {
  101. klog.Exitln("failed to get uname:", err)
  102. }
  103. klog.Infoln("hostname:", hostname)
  104. klog.Infoln("kernel version:", kv)
  105. ver := common.KernelMajorMinor(kv)
  106. if ver == "" {
  107. klog.Exitln("invalid kernel version:", kv)
  108. }
  109. if semver.Compare("v"+ver, "v"+minSupportedKernelVersion) == -1 {
  110. klog.Exitf("the minimum Linux kernel version required is %s or later", minSupportedKernelVersion)
  111. }
  112. whitelistNodeExternalNetworks()
  113. machineId := machineID()
  114. tracing.Init(machineId, hostname, version)
  115. logs.Init(machineId, hostname, version)
  116. registry := prometheus.NewRegistry()
  117. registerer := prometheus.WrapRegistererWith(prometheus.Labels{"machine_id": machineId}, registry)
  118. registerer.MustRegister(info("node_agent_info", version))
  119. if err := registerer.Register(node.NewCollector(hostname, kv)); err != nil {
  120. klog.Exitln(err)
  121. }
  122. //processInfoCh := profiling.Init(machineId, hostname)
  123. cr, err := containers.NewRegistry(registerer, kv, nil)
  124. if err != nil {
  125. klog.Exitln(err)
  126. }
  127. defer cr.Close()
  128. klog.Infoln("START_TRACE")
  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. }