main.go 17 KB

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