main.go 8.1 KB

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