main.go 16 KB

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