main.go 7.8 KB

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