main.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. "fmt"
  16. "io"
  17. "strconv"
  18. "time"
  19. "regexp"
  20. "encoding/json"
  21. dto "github.com/prometheus/client_model/go"
  22. "github.com/coroot/coroot-node-agent/common"
  23. "github.com/coroot/coroot-node-agent/containers"
  24. "github.com/coroot/coroot-node-agent/flags"
  25. "github.com/coroot/coroot-node-agent/logs"
  26. "github.com/coroot/coroot-node-agent/node"
  27. "github.com/coroot/coroot-node-agent/prom"
  28. "github.com/coroot/coroot-node-agent/tracing"
  29. "github.com/prometheus/client_golang/prometheus"
  30. "github.com/prometheus/client_golang/prometheus/promhttp"
  31. "golang.org/x/mod/semver"
  32. "golang.org/x/sys/unix"
  33. "golang.org/x/time/rate"
  34. )
  35. var (
  36. version = "unknown"
  37. // sendNetDataInterval = 1 * time.Minute
  38. )
  39. const minSupportedKernelVersion = "4.18"
  40. func init() {
  41. logs.FormatterInit()
  42. }
  43. func uname() (string, string, error) {
  44. runtime.LockOSThread()
  45. defer runtime.UnlockOSThread()
  46. f, err := os.Open("/proc/1/ns/uts")
  47. if err != nil {
  48. return "", "", err
  49. }
  50. defer f.Close()
  51. self, err := os.Open("/proc/self/ns/uts")
  52. if err != nil {
  53. return "", "", err
  54. }
  55. defer self.Close()
  56. defer func() {
  57. unix.Setns(int(self.Fd()), unix.CLONE_NEWUTS)
  58. }()
  59. err = unix.Setns(int(f.Fd()), unix.CLONE_NEWUTS)
  60. if err != nil {
  61. return "", "", err
  62. }
  63. var utsname unix.Utsname
  64. if err := unix.Uname(&utsname); err != nil {
  65. return "", "", err
  66. }
  67. hostname := string(bytes.Split(utsname.Nodename[:], []byte{0})[0])
  68. kernelVersion := string(bytes.Split(utsname.Release[:], []byte{0})[0])
  69. return hostname, kernelVersion, nil
  70. }
  71. func machineID() string {
  72. for _, p := range []string{"sys/devices/virtual/dmi/id/product_uuid", "etc/machine-id", "var/lib/dbus/machine-id"} {
  73. payload, err := os.ReadFile(path.Join("/proc/1/root", p))
  74. if err != nil {
  75. log.Warningln("failed to read machine-id:", err)
  76. continue
  77. }
  78. id := strings.TrimSpace(strings.Replace(string(payload), "-", "", -1))
  79. log.Infoln("machine-id: ", id)
  80. return id
  81. }
  82. return ""
  83. }
  84. func whitelistNodeExternalNetworks() {
  85. netdevs, err := node.NetDevices()
  86. if err != nil {
  87. log.Warningln("failed to get network interfaces:", err)
  88. return
  89. }
  90. for _, iface := range netdevs {
  91. for _, p := range iface.IPPrefixes {
  92. if p.IP().IsLoopback() || common.IsIpPrivate(p.IP()) {
  93. continue
  94. }
  95. // if the node has an external network IP, whitelist that network
  96. common.ConnectionFilter.WhitelistPrefix(p)
  97. }
  98. }
  99. }
  100. type MetricItemData struct {
  101. Label map[string]string `json:"metric_tags"`
  102. Value any `json:"value"`
  103. }
  104. type MetricData struct {
  105. MetricKey string `json:"metric_key"`
  106. Metric []MetricItemData `json:"metric"`
  107. }
  108. type PostData struct {
  109. AccountID string `json:"accountId"`
  110. IP string `json:"ip"`
  111. HostID int64 `json:"hostId"`
  112. TimeStamp uint64 `json:"time_stamp"`
  113. ServiceType uint64 `json:"service_type"`
  114. HostName string `json:"host_name"`
  115. Data []MetricData `json:"data"`
  116. }
  117. func main() {
  118. runtime.GOMAXPROCS(1)
  119. err := logs.InitLog(*flags.LogLevel, logs.LogConfig{
  120. Path: utils.GetDefaultLogPath(),
  121. AppInfo: enums.DaemonProc,
  122. MaxSize: 50, // 日志文件最大尺寸,单位MB
  123. MaxBackups: 3, // 最多保留的旧日志文件数
  124. MaxAge: 3, // 日志文件保留的最长时间,单位天
  125. Console: true,
  126. })
  127. if err != nil {
  128. log.WithError(err).Errorf("log init error.")
  129. }
  130. if err := rlimit.RemoveMemlock(); err != nil {
  131. log.WithError(err).Warning("Failed Removing memlock.")
  132. } else {
  133. log.Info("Rlimit removed")
  134. }
  135. //log.LogToStderr(false)
  136. //log.SetOutput(&RateLimitedLogOutput{limiter: rate.NewLimiter(rate.Limit(*flags.LogPerSecond), *flags.LogBurst)})
  137. log.Infoln("agent version:", version)
  138. hostname, kv, err := uname()
  139. if err != nil {
  140. log.Fatalln("failed to get uname:", err)
  141. }
  142. log.Infoln("hostname:", hostname)
  143. log.Infoln("kernel version:", kv)
  144. // 构建节点信息
  145. nodeInfo, err := node.NewNodeInfo(hostname, kv)
  146. if err != nil || nodeInfo == nil {
  147. log.Fatalln(err)
  148. }
  149. log.Infof("node info %s", utils.ToString(nodeInfo))
  150. ver := common.KernelMajorMinor(kv)
  151. if ver == "" {
  152. log.Fatalln("invalid kernel version:", kv)
  153. }
  154. if semver.Compare("v"+ver, "v"+minSupportedKernelVersion) == -1 {
  155. log.Fatalf("the minimum Linux kernel version required is %s or later", minSupportedKernelVersion)
  156. }
  157. whitelistNodeExternalNetworks()
  158. machineId := nodeInfo.GetNodeInfo().SystemUUID
  159. tracing.Init(machineId, hostname, version)
  160. logs.Init(machineId, hostname, version)
  161. if *flags.RunInContainer {
  162. _, err = kube.NewKubeClient()
  163. if err != nil {
  164. log.WithError(err).Errorf("Failed to init kube client.")
  165. }
  166. }
  167. registry := prometheus.NewRegistry()
  168. registerer := prometheus.WrapRegistererWith(prometheus.Labels{"machine_id": machineId}, registry)
  169. registerer.MustRegister(info("node_agent_info", version))
  170. if err := registerer.Register(node.NewCollector(hostname, kv)); err != nil {
  171. log.Fatalln(err)
  172. }
  173. //processInfoCh := profiling.Init(machineId, hostname)
  174. cr, err := containers.NewRegistry(registerer, kv, nodeInfo, nil)
  175. if err != nil {
  176. log.Fatalln(err)
  177. }
  178. defer cr.Close()
  179. log.Infoln("START_TRACE")
  180. //profiling.Start()
  181. //defer profiling.Stop()
  182. // 创建一个/metrics路由处理函数
  183. metricsHandler := func(w http.ResponseWriter, r *http.Request) {
  184. // 从注册表中获取指标数据
  185. metrics, err := registry.Gather()
  186. if err != nil {
  187. // 错误处理
  188. http.Error(w, err.Error(), http.StatusInternalServerError)
  189. return
  190. }
  191. // 创建正则表达式对象
  192. regex, err := regexp.Compile(`^process_.+_queries_total$`)
  193. if err != nil {
  194. return
  195. }
  196. var postData PostData
  197. postData.AccountID = strconv.Itoa(nodeInfo.AccountID)
  198. postData.IP = nodeInfo.HostIp
  199. postData.HostID = nodeInfo.HostID
  200. postData.TimeStamp = uint64(time.Now().UnixNano())
  201. postData.ServiceType = 30002
  202. postData.HostName = nodeInfo.Hostname
  203. for _, metric := range metrics {
  204. if metric.GetName() != "process_net_tcp_successful_connects_total" &&
  205. metric.GetName() != "process_net_tcp_failed_connects_total" &&
  206. metric.GetName() != "process_net_tcp_retransmits_total" &&
  207. metric.GetName() != "process_net_tcp_listen_info" &&
  208. metric.GetName() != "process_http_requests_total" &&
  209. metric.GetName() != "process_http_requests_duration_seconds_total" &&
  210. metric.GetName() != "process_http_requests_duration_seconds_total_count" &&
  211. // metric.GetName() != "process_mysql_queries_total" &&
  212. // metric.GetName() != "process_mysql_queries_duration_seconds_total" &&
  213. // metric.GetName() != "process_mysql_queries_duration_seconds_total_count" &&
  214. // metric.GetName() != "process_redis_queries_total" &&
  215. // metric.GetName() != "process_redis_queries_duration_seconds_total" &&
  216. // metric.GetName() != "process_redis_queries_duration_seconds_total_count" &&
  217. // metric.GetName() != "process_postgres_queries_total" &&
  218. // metric.GetName() != "process_postgres_queries_duration_seconds_total" &&
  219. // metric.GetName() != "process_postgres_queries_duration_seconds_total_count" &&
  220. regex.MatchString(metric.GetName()) == false &&
  221. metric.GetName() != "process_application_type" &&
  222. metric.GetName() != "process_net_tcp_bytes_received_per" &&
  223. metric.GetName() != "process_net_tcp_bytes_sent_per" &&
  224. metric.GetName() != "process_net_tcp_bytes_received_total" &&
  225. metric.GetName() != "process_net_tcp_bytes_sent_total" &&
  226. metric.GetName() != "process_net_tcp_data_latency" &&
  227. metric.GetName() != "process_net_tcp_data_duration" &&
  228. metric.GetName() != "process_net_tcp_est_time"{
  229. continue
  230. }
  231. var item MetricData
  232. var itemOther MetricData
  233. item.MetricKey = metric.GetName()
  234. for _, m := range metric.GetMetric() {
  235. metricItem := MetricItemData{}
  236. label := make(map[string]string)
  237. for _, l := range m.GetLabel() {
  238. label[l.GetName()] = l.GetValue()
  239. }
  240. metricItem.Label = label
  241. switch metric.GetType() {
  242. case dto.MetricType_COUNTER:
  243. metricItem.Value = m.GetCounter().GetValue()
  244. item.Metric = append(item.Metric, metricItem)
  245. case dto.MetricType_GAUGE:
  246. metricItem.Value = m.GetGauge().GetValue()
  247. item.Metric = append(item.Metric, metricItem)
  248. case dto.MetricType_HISTOGRAM:
  249. item.MetricKey = metric.GetName() + "_sum"
  250. metricItem.Value = m.GetHistogram().GetSampleSum()
  251. item.Metric = append(item.Metric, metricItem)
  252. metricItemOther := MetricItemData{}
  253. metricItemOther.Label = label
  254. itemOther.MetricKey = metric.GetName() + "_count"
  255. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  256. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  257. default:
  258. continue
  259. }
  260. }
  261. postData.Data = append(postData.Data, item)
  262. if metric.GetType() == dto.MetricType_HISTOGRAM {
  263. postData.Data = append(postData.Data, itemOther)
  264. }
  265. }
  266. // 将指标数据转换为JSON格式
  267. jsonData, err := json.Marshal(postData)
  268. //jsonData, err := json.Marshal(metrics)
  269. if err != nil {
  270. http.Error(w, err.Error(), http.StatusInternalServerError)
  271. return
  272. }
  273. w.Header().Set("Content-Type", "application/json")
  274. w.Write(jsonData)
  275. // 创建请求
  276. req, err := http.NewRequest("POST", "http://10.0.7.115:18080/api/v2/ebpf/receive", bytes.NewBuffer(jsonData))
  277. if err != nil {
  278. fmt.Println("Error:", err)
  279. return
  280. }
  281. // 添加 Content-Type header
  282. req.Header.Add("Content-Type", "application/json")
  283. // 添加一个自定义 header
  284. req.Header.Add("DataCount", strconv.Itoa(len(postData.Data)))
  285. req.Header.Add("Account-Id", strconv.Itoa(nodeInfo.AccountID))
  286. req.Header.Add("ip", nodeInfo.HostIp)
  287. // 创建 HTTP 客户端
  288. client := &http.Client{}
  289. // 发送 HTTP POST 请求
  290. response, err := client.Do(req)
  291. if err != nil {
  292. fmt.Println("Error:", err)
  293. return
  294. }
  295. defer response.Body.Close()
  296. // 读取响应内容
  297. responseData, err := io.ReadAll(response.Body)
  298. if err != nil {
  299. fmt.Println("Error:", err)
  300. return
  301. }
  302. // 输出响应状态码和响应正文
  303. fmt.Println("Status Code:", response.StatusCode)
  304. fmt.Println("Response Body:", string(responseData))
  305. }
  306. if err := prom.StartAgent(machineId); err != nil {
  307. log.Fatalln(err)
  308. }
  309. // go func() {
  310. // ticker := time.NewTicker(sendNetDataInterval)
  311. // defer ticker.Stop()
  312. // for {
  313. // select {
  314. // case <-c.done:
  315. // return
  316. // case t := <-ticker.C:
  317. // c.gc(t)
  318. // }
  319. // }
  320. // }()
  321. http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: logger{}, Registry: registerer}))
  322. http.HandleFunc("/metrics2", metricsHandler)
  323. log.Infoln("listening on:", *flags.ListenAddress)
  324. log.Errorln(http.ListenAndServe(*flags.ListenAddress, nil))
  325. }
  326. func info(name, version string) prometheus.Collector {
  327. g := prometheus.NewGauge(prometheus.GaugeOpts{
  328. Name: name,
  329. ConstLabels: prometheus.Labels{"version": version},
  330. })
  331. g.Set(1)
  332. return g
  333. }
  334. type logger struct{}
  335. func (l logger) Println(v ...interface{}) {
  336. log.Errorln(v...)
  337. }
  338. type RateLimitedLogOutput struct {
  339. limiter *rate.Limiter
  340. }
  341. func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
  342. if !o.limiter.Allow() {
  343. return len(data), nil
  344. }
  345. return os.Stderr.Write(data)
  346. }