main.go 7.5 KB

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