main.go 17 KB

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