main.go 7.9 KB

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