main.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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(*flags.LogLevel, 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 := utils.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. nodeInfo, err := node.NewNodeInfo(hostname, kv, machineId)
  140. if err != nil || nodeInfo == nil {
  141. log.Fatalln(err)
  142. }
  143. cr, err := containers.NewRegistry(registerer, kv, nodeInfo, nil)
  144. if err != nil {
  145. log.Fatalln(err)
  146. }
  147. defer cr.Close()
  148. log.Infoln("START_TRACE")
  149. //profiling.Start()
  150. //defer profiling.Stop()
  151. // 创建一个/metrics路由处理函数
  152. metricsHandler := func(w http.ResponseWriter, r *http.Request) {
  153. // 从注册表中获取指标数据
  154. metrics, err := registry.Gather()
  155. if err != nil {
  156. // 错误处理
  157. http.Error(w, err.Error(), http.StatusInternalServerError)
  158. return
  159. }
  160. var Data []MetricData
  161. for _, metric := range metrics {
  162. if metric.GetName() != "container_net_tcp_successful_connects_total" &&
  163. metric.GetName() != "container_net_tcp_failed_connects_total" &&
  164. metric.GetName() != "container_net_tcp_retransmits_total" &&
  165. metric.GetName() != "container_net_tcp_listen_info" &&
  166. metric.GetName() != "container_http_requests_total" &&
  167. metric.GetName() != "container_http_requests_duration_seconds_total" &&
  168. metric.GetName() != "container_application_type" {
  169. continue
  170. }
  171. var item MetricData
  172. var itemOther MetricData
  173. item.MetricKey = metric.GetName()
  174. for _, m := range metric.GetMetric() {
  175. metricItem := MetricItemData{}
  176. label := make(map[string]string)
  177. for _, l := range m.GetLabel() {
  178. label[l.GetName()] = l.GetValue()
  179. }
  180. metricItem.Label = label
  181. switch metric.GetType() {
  182. case dto.MetricType_COUNTER:
  183. metricItem.Value = m.GetCounter().GetValue()
  184. item.Metric = append(item.Metric, metricItem)
  185. case dto.MetricType_GAUGE:
  186. metricItem.Value = m.GetGauge().GetValue()
  187. item.Metric = append(item.Metric, metricItem)
  188. case dto.MetricType_HISTOGRAM:
  189. item.MetricKey = metric.GetName() + "_sum"
  190. metricItem.Value = m.GetHistogram().GetSampleSum()
  191. item.Metric = append(item.Metric, metricItem)
  192. metricItemOther := MetricItemData{}
  193. metricItemOther.Label = label
  194. itemOther.MetricKey = metric.GetName() + "_count"
  195. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  196. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  197. default:
  198. continue
  199. }
  200. }
  201. Data = append(Data, item)
  202. if metric.GetType() == dto.MetricType_HISTOGRAM {
  203. Data = append(Data, itemOther)
  204. }
  205. }
  206. // 将指标数据转换为JSON格式
  207. jsonData, err := json.Marshal(Data)
  208. //jsonData, err := json.Marshal(metrics)
  209. if err != nil {
  210. http.Error(w, err.Error(), http.StatusInternalServerError)
  211. return
  212. }
  213. w.Header().Set("Content-Type", "application/json")
  214. w.Write(jsonData)
  215. }
  216. if err := prom.StartAgent(machineId); err != nil {
  217. log.Fatalln(err)
  218. }
  219. http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: logger{}, Registry: registerer}))
  220. http.HandleFunc("/metrics2", metricsHandler)
  221. log.Infoln("listening on:", *flags.ListenAddress)
  222. log.Errorln(http.ListenAndServe(*flags.ListenAddress, nil))
  223. }
  224. func info(name, version string) prometheus.Collector {
  225. g := prometheus.NewGauge(prometheus.GaugeOpts{
  226. Name: name,
  227. ConstLabels: prometheus.Labels{"version": version},
  228. })
  229. g.Set(1)
  230. return g
  231. }
  232. type logger struct{}
  233. func (l logger) Println(v ...interface{}) {
  234. log.Errorln(v...)
  235. }
  236. type RateLimitedLogOutput struct {
  237. limiter *rate.Limiter
  238. }
  239. func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
  240. if !o.limiter.Allow() {
  241. return len(data), nil
  242. }
  243. return os.Stderr.Write(data)
  244. }