main.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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_time" &&
  241. metric.GetName() != "process_net_tcp_flow_duration_time" &&
  242. metric.GetName() != "process_net_tcp_connection_establish_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.DataServer + *flags.ServerPrefix + 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.DataServer + *flags.ServerPrefix + 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. log.Infoln("Error:", err)
  315. return
  316. }
  317. // 输出响应状态码和响应正文
  318. log.Infoln("Status Code:", response.StatusCode)
  319. log.Infoln("Response Body:", string(responseData))
  320. }
  321. sendNetDataDone := make(chan struct{})
  322. go func() {
  323. sendNetDataTicker := time.NewTicker(sendNetDataInterval)
  324. defer sendNetDataTicker.Stop()
  325. for {
  326. select {
  327. case <-sendNetDataDone:
  328. return
  329. case _ = <-sendNetDataTicker.C:
  330. sendNetDataFunc()
  331. }
  332. }
  333. }()
  334. metricsHandler := func(w http.ResponseWriter, r *http.Request) {
  335. // 从注册表中获取指标数据
  336. metrics, err := registry.Gather()
  337. if err != nil {
  338. // 错误处理
  339. http.Error(w, err.Error(), http.StatusInternalServerError)
  340. return
  341. }
  342. // 创建正则表达式对象
  343. regex, err := regexp.Compile(`^process_.+_queries_total$`)
  344. if err != nil {
  345. return
  346. }
  347. var postData PostData
  348. postData.AccountID = strconv.Itoa(nodeInfo.AccountID)
  349. postData.IP = nodeInfo.HostIp
  350. postData.HostID = nodeInfo.HostID
  351. postData.TimeStamp = uint64(time.Now().UnixNano())
  352. postData.ServiceType = 30002
  353. postData.HostName = nodeInfo.Hostname
  354. for _, metric := range metrics {
  355. if metric.GetName() != "process_net_tcp_successful_connects_total" &&
  356. metric.GetName() != "process_net_tcp_failed_connects_total" &&
  357. metric.GetName() != "process_net_tcp_retransmits_total" &&
  358. metric.GetName() != "process_net_tcp_listen_info" &&
  359. metric.GetName() != "process_http_requests_total" &&
  360. metric.GetName() != "process_http_requests_duration_seconds_total" &&
  361. metric.GetName() != "process_http_requests_duration_seconds_total_count" &&
  362. // metric.GetName() != "process_mysql_queries_total" &&
  363. // metric.GetName() != "process_mysql_queries_duration_seconds_total" &&
  364. // metric.GetName() != "process_mysql_queries_duration_seconds_total_count" &&
  365. // metric.GetName() != "process_redis_queries_total" &&
  366. // metric.GetName() != "process_redis_queries_duration_seconds_total" &&
  367. // metric.GetName() != "process_redis_queries_duration_seconds_total_count" &&
  368. // metric.GetName() != "process_postgres_queries_total" &&
  369. // metric.GetName() != "process_postgres_queries_duration_seconds_total" &&
  370. // metric.GetName() != "process_postgres_queries_duration_seconds_total_count" &&
  371. regex.MatchString(metric.GetName()) == false &&
  372. metric.GetName() != "process_application_type" &&
  373. metric.GetName() != "process_net_tcp_bytes_received_per" &&
  374. metric.GetName() != "process_net_tcp_bytes_sent_per" &&
  375. metric.GetName() != "process_net_tcp_bytes_received_total" &&
  376. metric.GetName() != "process_net_tcp_bytes_sent_total" &&
  377. metric.GetName() != "process_net_tcp_data_latency" &&
  378. metric.GetName() != "process_net_tcp_data_duration" &&
  379. metric.GetName() != "process_net_tcp_est_time" {
  380. continue
  381. }
  382. var item MetricData
  383. var itemOther MetricData
  384. item.MetricKey = metric.GetName()
  385. for _, m := range metric.GetMetric() {
  386. metricItem := MetricItemData{}
  387. label := make(map[string]string)
  388. for _, l := range m.GetLabel() {
  389. label[l.GetName()] = l.GetValue()
  390. }
  391. metricItem.Label = label
  392. switch metric.GetType() {
  393. case dto.MetricType_COUNTER:
  394. metricItem.Value = m.GetCounter().GetValue()
  395. item.Metric = append(item.Metric, metricItem)
  396. case dto.MetricType_GAUGE:
  397. metricItem.Value = m.GetGauge().GetValue()
  398. item.Metric = append(item.Metric, metricItem)
  399. case dto.MetricType_HISTOGRAM:
  400. item.MetricKey = metric.GetName() + "_sum"
  401. metricItem.Value = m.GetHistogram().GetSampleSum()
  402. item.Metric = append(item.Metric, metricItem)
  403. metricItemOther := MetricItemData{}
  404. metricItemOther.Label = label
  405. itemOther.MetricKey = metric.GetName() + "_count"
  406. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  407. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  408. default:
  409. continue
  410. }
  411. }
  412. postData.Data = append(postData.Data, item)
  413. if metric.GetType() == dto.MetricType_HISTOGRAM {
  414. postData.Data = append(postData.Data, itemOther)
  415. }
  416. }
  417. // 将指标数据转换为JSON格式
  418. jsonData, err := json.Marshal(postData)
  419. //jsonData, err := json.Marshal(metrics)
  420. if err != nil {
  421. http.Error(w, err.Error(), http.StatusInternalServerError)
  422. return
  423. }
  424. w.Header().Set("Content-Type", "application/json")
  425. w.Write(jsonData)
  426. // 创建请求
  427. req, err := http.NewRequest("POST", "http://10.0.7.115:18080/api/v2/ebpf/receive", bytes.NewBuffer(jsonData))
  428. if err != nil {
  429. fmt.Println("Error:", err)
  430. return
  431. }
  432. // 添加 Content-Type header
  433. req.Header.Add("Content-Type", "application/json")
  434. // 添加一个自定义 header
  435. req.Header.Add("DataCount", strconv.Itoa(len(postData.Data)))
  436. req.Header.Add("Account-Id", strconv.Itoa(nodeInfo.AccountID))
  437. req.Header.Add("ip", nodeInfo.HostIp)
  438. // 创建 HTTP 客户端
  439. client := &http.Client{}
  440. // 发送 HTTP POST 请求
  441. response, err := client.Do(req)
  442. if err != nil {
  443. fmt.Println("Error:", err)
  444. return
  445. }
  446. defer response.Body.Close()
  447. // 读取响应内容
  448. responseData, err := io.ReadAll(response.Body)
  449. if err != nil {
  450. fmt.Println("Error:", err)
  451. return
  452. }
  453. // 输出响应状态码和响应正文
  454. fmt.Println("Status Code:", response.StatusCode)
  455. fmt.Println("Response Body:", string(responseData))
  456. }
  457. if err := prom.StartAgent(machineId); err != nil {
  458. log.Fatalln(err)
  459. }
  460. http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: logger{}, Registry: registerer}))
  461. http.HandleFunc("/metrics2", metricsHandler)
  462. log.Infoln("listening on:", *flags.ListenAddress)
  463. log.Errorln(http.ListenAndServe(*flags.ListenAddress, nil))
  464. close(sendNetDataDone)
  465. }
  466. func info(name, version string) prometheus.Collector {
  467. g := prometheus.NewGauge(prometheus.GaugeOpts{
  468. Name: name,
  469. ConstLabels: prometheus.Labels{"version": version},
  470. })
  471. g.Set(1)
  472. return g
  473. }
  474. type logger struct{}
  475. func (l logger) Println(v ...interface{}) {
  476. log.Errorln(v...)
  477. }
  478. type RateLimitedLogOutput struct {
  479. limiter *rate.Limiter
  480. }
  481. func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
  482. if !o.limiter.Allow() {
  483. return len(data), nil
  484. }
  485. return os.Stderr.Write(data)
  486. }