main.go 7.4 KB

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