main.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. package main
  2. import (
  3. "bytes"
  4. "github.com/cilium/ebpf/rlimit"
  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.18"
  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. runtime.GOMAXPROCS(1)
  103. err := logs.InitLog(*flags.LogLevel, logs.LogConfig{
  104. Path: utils.GetDefaultLogPath(),
  105. AppInfo: enums.DaemonProc,
  106. MaxSize: 50, // 日志文件最大尺寸,单位MB
  107. MaxBackups: 3, // 最多保留的旧日志文件数
  108. MaxAge: 3, // 日志文件保留的最长时间,单位天
  109. Console: true,
  110. })
  111. if err != nil {
  112. log.WithError(err).Errorf("log init error.")
  113. }
  114. if err := rlimit.RemoveMemlock(); err != nil {
  115. log.WithError(err).Warning("Failed Removing memlock.")
  116. } else {
  117. log.Info("Rlimit removed")
  118. }
  119. //log.LogToStderr(false)
  120. //log.SetOutput(&RateLimitedLogOutput{limiter: rate.NewLimiter(rate.Limit(*flags.LogPerSecond), *flags.LogBurst)})
  121. log.Infoln("agent version:", version)
  122. hostname, kv, err := uname()
  123. if err != nil {
  124. log.Fatalln("failed to get uname:", err)
  125. }
  126. log.Infoln("hostname:", hostname)
  127. log.Infoln("kernel version:", kv)
  128. // 构建节点信息
  129. nodeInfo, err := node.NewNodeInfo(hostname, kv)
  130. if err != nil || nodeInfo == nil {
  131. log.Fatalln(err)
  132. }
  133. log.Infof("node info %s", utils.ToString(nodeInfo))
  134. ver := common.KernelMajorMinor(kv)
  135. if ver == "" {
  136. log.Fatalln("invalid kernel version:", kv)
  137. }
  138. if semver.Compare("v"+ver, "v"+minSupportedKernelVersion) == -1 {
  139. log.Fatalf("the minimum Linux kernel version required is %s or later", minSupportedKernelVersion)
  140. }
  141. whitelistNodeExternalNetworks()
  142. machineId := nodeInfo.GetNodeInfo().SystemUUID
  143. tracing.Init(machineId, hostname, version)
  144. logs.Init(machineId, hostname, version)
  145. registry := prometheus.NewRegistry()
  146. registerer := prometheus.WrapRegistererWith(prometheus.Labels{"machine_id": machineId}, registry)
  147. registerer.MustRegister(info("node_agent_info", version))
  148. if err := registerer.Register(node.NewCollector(hostname, kv)); err != nil {
  149. log.Fatalln(err)
  150. }
  151. //processInfoCh := profiling.Init(machineId, hostname)
  152. cr, err := containers.NewRegistry(registerer, kv, nodeInfo, nil)
  153. if err != nil {
  154. log.Fatalln(err)
  155. }
  156. defer cr.Close()
  157. log.Infoln("START_TRACE")
  158. //profiling.Start()
  159. //defer profiling.Stop()
  160. // 创建一个/metrics路由处理函数
  161. metricsHandler := func(w http.ResponseWriter, r *http.Request) {
  162. // 从注册表中获取指标数据
  163. metrics, err := registry.Gather()
  164. if err != nil {
  165. // 错误处理
  166. http.Error(w, err.Error(), http.StatusInternalServerError)
  167. return
  168. }
  169. var Data []MetricData
  170. for _, metric := range metrics {
  171. if metric.GetName() != "container_net_tcp_successful_connects_total" &&
  172. metric.GetName() != "container_net_tcp_failed_connects_total" &&
  173. metric.GetName() != "container_net_tcp_retransmits_total" &&
  174. metric.GetName() != "container_net_tcp_listen_info" &&
  175. metric.GetName() != "container_http_requests_total" &&
  176. metric.GetName() != "container_http_requests_duration_seconds_total" &&
  177. metric.GetName() != "container_application_type" {
  178. continue
  179. }
  180. var item MetricData
  181. var itemOther MetricData
  182. item.MetricKey = metric.GetName()
  183. for _, m := range metric.GetMetric() {
  184. metricItem := MetricItemData{}
  185. label := make(map[string]string)
  186. for _, l := range m.GetLabel() {
  187. label[l.GetName()] = l.GetValue()
  188. }
  189. metricItem.Label = label
  190. switch metric.GetType() {
  191. case dto.MetricType_COUNTER:
  192. metricItem.Value = m.GetCounter().GetValue()
  193. item.Metric = append(item.Metric, metricItem)
  194. case dto.MetricType_GAUGE:
  195. metricItem.Value = m.GetGauge().GetValue()
  196. item.Metric = append(item.Metric, metricItem)
  197. case dto.MetricType_HISTOGRAM:
  198. item.MetricKey = metric.GetName() + "_sum"
  199. metricItem.Value = m.GetHistogram().GetSampleSum()
  200. item.Metric = append(item.Metric, metricItem)
  201. metricItemOther := MetricItemData{}
  202. metricItemOther.Label = label
  203. itemOther.MetricKey = metric.GetName() + "_count"
  204. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  205. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  206. default:
  207. continue
  208. }
  209. }
  210. Data = append(Data, item)
  211. if metric.GetType() == dto.MetricType_HISTOGRAM {
  212. Data = append(Data, itemOther)
  213. }
  214. }
  215. // 将指标数据转换为JSON格式
  216. jsonData, err := json.Marshal(Data)
  217. //jsonData, err := json.Marshal(metrics)
  218. if err != nil {
  219. http.Error(w, err.Error(), http.StatusInternalServerError)
  220. return
  221. }
  222. w.Header().Set("Content-Type", "application/json")
  223. w.Write(jsonData)
  224. }
  225. if err := prom.StartAgent(machineId); err != nil {
  226. log.Fatalln(err)
  227. }
  228. http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: logger{}, Registry: registerer}))
  229. http.HandleFunc("/metrics2", metricsHandler)
  230. log.Infoln("listening on:", *flags.ListenAddress)
  231. log.Errorln(http.ListenAndServe(*flags.ListenAddress, nil))
  232. }
  233. func info(name, version string) prometheus.Collector {
  234. g := prometheus.NewGauge(prometheus.GaugeOpts{
  235. Name: name,
  236. ConstLabels: prometheus.Labels{"version": version},
  237. })
  238. g.Set(1)
  239. return g
  240. }
  241. type logger struct{}
  242. func (l logger) Println(v ...interface{}) {
  243. log.Errorln(v...)
  244. }
  245. type RateLimitedLogOutput struct {
  246. limiter *rate.Limiter
  247. }
  248. func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
  249. if !o.limiter.Allow() {
  250. return len(data), nil
  251. }
  252. return os.Stderr.Write(data)
  253. }