main.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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.Errorf("get namedpipeCtl occurs error: %s", err.Error())
  188. } else {
  189. //监听&处理-熔断信号
  190. npCtl.AcceptAndDisposeMsg(cr)
  191. }
  192. }
  193. //heartbeat
  194. try.GoParams(containers.DoHeartbeat, utils.CatchFn, filepath.Join(utils.GetRootPath(), "heartbeat"))
  195. //profiling.Start()
  196. //defer profiling.Stop()
  197. // 创建一个/metrics路由处理函数
  198. sendNetDataFunc := func() {
  199. // 从注册表中获取指标数据
  200. metrics, err := registry.Gather()
  201. if err != nil {
  202. // 错误处理
  203. return
  204. }
  205. // 创建正则表达式对象
  206. regex, err := regexp.Compile(`^process_.+_queries_total$`)
  207. if err != nil {
  208. return
  209. }
  210. var postData PostData
  211. postData.AccountID = strconv.Itoa(nodeInfo.AccountID)
  212. postData.IP = nodeInfo.HostIp
  213. postData.HostID = nodeInfo.HostID
  214. postData.TimeStamp = uint64(time.Now().UnixNano())
  215. postData.ServiceType = 30002
  216. postData.HostName = nodeInfo.Hostname
  217. for _, metric := range metrics {
  218. if metric.GetName() != "process_net_tcp_successful_connects_total" &&
  219. metric.GetName() != "process_net_tcp_failed_connects_total" &&
  220. metric.GetName() != "process_net_tcp_retransmits_total" &&
  221. metric.GetName() != "process_net_tcp_listen_info" &&
  222. metric.GetName() != "process_http_requests_total" &&
  223. metric.GetName() != "process_http_requests_duration_seconds_total" &&
  224. metric.GetName() != "process_http_requests_duration_seconds_total_count" &&
  225. // metric.GetName() != "process_mysql_queries_total" &&
  226. // metric.GetName() != "process_mysql_queries_duration_seconds_total" &&
  227. // metric.GetName() != "process_mysql_queries_duration_seconds_total_count" &&
  228. // metric.GetName() != "process_redis_queries_total" &&
  229. // metric.GetName() != "process_redis_queries_duration_seconds_total" &&
  230. // metric.GetName() != "process_redis_queries_duration_seconds_total_count" &&
  231. // metric.GetName() != "process_postgres_queries_total" &&
  232. // metric.GetName() != "process_postgres_queries_duration_seconds_total" &&
  233. // metric.GetName() != "process_postgres_queries_duration_seconds_total_count" &&
  234. regex.MatchString(metric.GetName()) == false &&
  235. metric.GetName() != "process_application_type" &&
  236. metric.GetName() != "process_net_tcp_bytes_received_per" &&
  237. metric.GetName() != "process_net_tcp_bytes_sent_per" &&
  238. metric.GetName() != "process_net_tcp_bytes_received_total" &&
  239. metric.GetName() != "process_net_tcp_bytes_sent_total" &&
  240. metric.GetName() != "process_net_tcp_data_latency" &&
  241. metric.GetName() != "process_net_tcp_data_duration" &&
  242. metric.GetName() != "process_net_tcp_est_time" {
  243. continue
  244. }
  245. var item MetricData
  246. var itemOther MetricData
  247. item.MetricKey = metric.GetName()
  248. for _, m := range metric.GetMetric() {
  249. metricItem := MetricItemData{}
  250. label := make(map[string]string)
  251. for _, l := range m.GetLabel() {
  252. label[l.GetName()] = l.GetValue()
  253. }
  254. metricItem.Label = label
  255. switch metric.GetType() {
  256. case dto.MetricType_COUNTER:
  257. metricItem.Value = m.GetCounter().GetValue()
  258. item.Metric = append(item.Metric, metricItem)
  259. case dto.MetricType_GAUGE:
  260. metricItem.Value = m.GetGauge().GetValue()
  261. item.Metric = append(item.Metric, metricItem)
  262. case dto.MetricType_HISTOGRAM:
  263. item.MetricKey = metric.GetName() + "_sum"
  264. metricItem.Value = m.GetHistogram().GetSampleSum()
  265. item.Metric = append(item.Metric, metricItem)
  266. metricItemOther := MetricItemData{}
  267. metricItemOther.Label = label
  268. itemOther.MetricKey = metric.GetName() + "_count"
  269. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  270. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  271. default:
  272. continue
  273. }
  274. }
  275. postData.Data = append(postData.Data, item)
  276. if metric.GetType() == dto.MetricType_HISTOGRAM {
  277. postData.Data = append(postData.Data, itemOther)
  278. }
  279. }
  280. // 将指标数据转换为JSON格式
  281. jsonData, err := json.Marshal(postData)
  282. //jsonData, err := json.Marshal(metrics)
  283. if err != nil {
  284. return
  285. }
  286. log.Infoln("netdata is:", string(jsonData))
  287. // 创建请求
  288. urlRoute := "/api/v2/ebpf/receive"
  289. log.Infoln("send url is ", *flags.ServerPrefix + *flags.DataServer + urlRoute)
  290. // req, err := http.NewRequest("POST", "http://10.0.7.115:18080/api/v2/ebpf/receive", bytes.NewBuffer(jsonData))
  291. req, err := http.NewRequest("POST", *flags.ServerPrefix + *flags.DataServer + urlRoute, bytes.NewBuffer(jsonData))
  292. if err != nil {
  293. fmt.Println("Error:", err)
  294. return
  295. }
  296. // 添加 Content-Type header
  297. req.Header.Add("Content-Type", "application/json")
  298. // 添加一个自定义 header
  299. req.Header.Add("DataCount", strconv.Itoa(len(postData.Data)))
  300. req.Header.Add("Account-Id", strconv.Itoa(nodeInfo.AccountID))
  301. req.Header.Add("ip", nodeInfo.HostIp)
  302. // 创建 HTTP 客户端
  303. client := &http.Client{}
  304. // 发送 HTTP POST 请求
  305. response, err := client.Do(req)
  306. if err != nil {
  307. fmt.Println("Error:", err)
  308. return
  309. }
  310. defer response.Body.Close()
  311. // 读取响应内容
  312. responseData, err := io.ReadAll(response.Body)
  313. if err != nil {
  314. fmt.Println("Error:", err)
  315. return
  316. }
  317. // 输出响应状态码和响应正文
  318. fmt.Println("Status Code:", response.StatusCode)
  319. fmt.Println("Response Body:", string(responseData))
  320. log.Infoln("send data response is ", string(responseData))
  321. }
  322. sendNetDataDone := make(chan struct{})
  323. go func() {
  324. sendNetDataTicker := time.NewTicker(sendNetDataInterval)
  325. defer sendNetDataTicker.Stop()
  326. for {
  327. select {
  328. case <-sendNetDataDone:
  329. return
  330. case _ = <-sendNetDataTicker.C:
  331. sendNetDataFunc()
  332. }
  333. }
  334. }()
  335. metricsHandler := func(w http.ResponseWriter, r *http.Request) {
  336. // 从注册表中获取指标数据
  337. metrics, err := registry.Gather()
  338. if err != nil {
  339. // 错误处理
  340. http.Error(w, err.Error(), http.StatusInternalServerError)
  341. return
  342. }
  343. // 创建正则表达式对象
  344. regex, err := regexp.Compile(`^process_.+_queries_total$`)
  345. if err != nil {
  346. return
  347. }
  348. var postData PostData
  349. postData.AccountID = strconv.Itoa(nodeInfo.AccountID)
  350. postData.IP = nodeInfo.HostIp
  351. postData.HostID = nodeInfo.HostID
  352. postData.TimeStamp = uint64(time.Now().UnixNano())
  353. postData.ServiceType = 30002
  354. postData.HostName = nodeInfo.Hostname
  355. for _, metric := range metrics {
  356. if metric.GetName() != "process_net_tcp_successful_connects_total" &&
  357. metric.GetName() != "process_net_tcp_failed_connects_total" &&
  358. metric.GetName() != "process_net_tcp_retransmits_total" &&
  359. metric.GetName() != "process_net_tcp_listen_info" &&
  360. metric.GetName() != "process_http_requests_total" &&
  361. metric.GetName() != "process_http_requests_duration_seconds_total" &&
  362. metric.GetName() != "process_http_requests_duration_seconds_total_count" &&
  363. // metric.GetName() != "process_mysql_queries_total" &&
  364. // metric.GetName() != "process_mysql_queries_duration_seconds_total" &&
  365. // metric.GetName() != "process_mysql_queries_duration_seconds_total_count" &&
  366. // metric.GetName() != "process_redis_queries_total" &&
  367. // metric.GetName() != "process_redis_queries_duration_seconds_total" &&
  368. // metric.GetName() != "process_redis_queries_duration_seconds_total_count" &&
  369. // metric.GetName() != "process_postgres_queries_total" &&
  370. // metric.GetName() != "process_postgres_queries_duration_seconds_total" &&
  371. // metric.GetName() != "process_postgres_queries_duration_seconds_total_count" &&
  372. regex.MatchString(metric.GetName()) == false &&
  373. metric.GetName() != "process_application_type" &&
  374. metric.GetName() != "process_net_tcp_bytes_received_per" &&
  375. metric.GetName() != "process_net_tcp_bytes_sent_per" &&
  376. metric.GetName() != "process_net_tcp_bytes_received_total" &&
  377. metric.GetName() != "process_net_tcp_bytes_sent_total" &&
  378. metric.GetName() != "process_net_tcp_data_latency" &&
  379. metric.GetName() != "process_net_tcp_data_duration" &&
  380. metric.GetName() != "process_net_tcp_est_time" {
  381. continue
  382. }
  383. var item MetricData
  384. var itemOther MetricData
  385. item.MetricKey = metric.GetName()
  386. for _, m := range metric.GetMetric() {
  387. metricItem := MetricItemData{}
  388. label := make(map[string]string)
  389. for _, l := range m.GetLabel() {
  390. label[l.GetName()] = l.GetValue()
  391. }
  392. metricItem.Label = label
  393. switch metric.GetType() {
  394. case dto.MetricType_COUNTER:
  395. metricItem.Value = m.GetCounter().GetValue()
  396. item.Metric = append(item.Metric, metricItem)
  397. case dto.MetricType_GAUGE:
  398. metricItem.Value = m.GetGauge().GetValue()
  399. item.Metric = append(item.Metric, metricItem)
  400. case dto.MetricType_HISTOGRAM:
  401. item.MetricKey = metric.GetName() + "_sum"
  402. metricItem.Value = m.GetHistogram().GetSampleSum()
  403. item.Metric = append(item.Metric, metricItem)
  404. metricItemOther := MetricItemData{}
  405. metricItemOther.Label = label
  406. itemOther.MetricKey = metric.GetName() + "_count"
  407. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  408. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  409. default:
  410. continue
  411. }
  412. }
  413. postData.Data = append(postData.Data, item)
  414. if metric.GetType() == dto.MetricType_HISTOGRAM {
  415. postData.Data = append(postData.Data, itemOther)
  416. }
  417. }
  418. // 将指标数据转换为JSON格式
  419. jsonData, err := json.Marshal(postData)
  420. //jsonData, err := json.Marshal(metrics)
  421. if err != nil {
  422. http.Error(w, err.Error(), http.StatusInternalServerError)
  423. return
  424. }
  425. w.Header().Set("Content-Type", "application/json")
  426. w.Write(jsonData)
  427. // 创建请求
  428. req, err := http.NewRequest("POST", "http://10.0.7.115:18080/api/v2/ebpf/receive", bytes.NewBuffer(jsonData))
  429. if err != nil {
  430. fmt.Println("Error:", err)
  431. return
  432. }
  433. // 添加 Content-Type header
  434. req.Header.Add("Content-Type", "application/json")
  435. // 添加一个自定义 header
  436. req.Header.Add("DataCount", strconv.Itoa(len(postData.Data)))
  437. req.Header.Add("Account-Id", strconv.Itoa(nodeInfo.AccountID))
  438. req.Header.Add("ip", nodeInfo.HostIp)
  439. // 创建 HTTP 客户端
  440. client := &http.Client{}
  441. // 发送 HTTP POST 请求
  442. response, err := client.Do(req)
  443. if err != nil {
  444. fmt.Println("Error:", err)
  445. return
  446. }
  447. defer response.Body.Close()
  448. // 读取响应内容
  449. responseData, err := io.ReadAll(response.Body)
  450. if err != nil {
  451. fmt.Println("Error:", err)
  452. return
  453. }
  454. // 输出响应状态码和响应正文
  455. fmt.Println("Status Code:", response.StatusCode)
  456. fmt.Println("Response Body:", string(responseData))
  457. }
  458. if err := prom.StartAgent(machineId); err != nil {
  459. log.Fatalln(err)
  460. }
  461. http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: logger{}, Registry: registerer}))
  462. http.HandleFunc("/metrics2", metricsHandler)
  463. log.Infoln("listening on:", *flags.ListenAddress)
  464. log.Errorln(http.ListenAndServe(*flags.ListenAddress, nil))
  465. close(sendNetDataDone)
  466. }
  467. func info(name, version string) prometheus.Collector {
  468. g := prometheus.NewGauge(prometheus.GaugeOpts{
  469. Name: name,
  470. ConstLabels: prometheus.Labels{"version": version},
  471. })
  472. g.Set(1)
  473. return g
  474. }
  475. type logger struct{}
  476. func (l logger) Println(v ...interface{}) {
  477. log.Errorln(v...)
  478. }
  479. type RateLimitedLogOutput struct {
  480. limiter *rate.Limiter
  481. }
  482. func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
  483. if !o.limiter.Allow() {
  484. return len(data), nil
  485. }
  486. return os.Stderr.Write(data)
  487. }