main.go 17 KB

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