main.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. package main
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io"
  6. "net/http"
  7. _ "net/http/pprof"
  8. "os"
  9. "os/signal"
  10. "path"
  11. "path/filepath"
  12. "syscall"
  13. "github.com/cilium/ebpf/rlimit"
  14. "github.com/coroot/coroot-node-agent/kube"
  15. "github.com/coroot/coroot-node-agent/utils"
  16. "github.com/coroot/coroot-node-agent/utils/namedpipe"
  17. "github.com/coroot/coroot-node-agent/utils/try"
  18. dto "github.com/prometheus/client_model/go"
  19. log "github.com/sirupsen/logrus"
  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/config"
  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. // 初始化配置文件(支持热加载)
  122. // 支持三种方式指定配置文件:
  123. // 1. 命令行参数 --config
  124. // 2. 环境变量 EUSPACE_CONFIG
  125. // 3. 自动查找默认位置的配置文件(如果存在)
  126. configPath := *flags.ConfigFile
  127. if configPath == "" {
  128. configPath = os.Getenv("EUSPACE_CONFIG")
  129. }
  130. var err error
  131. if err = config.InitConfig(configPath); err != nil {
  132. log.Warnf("Failed to initialize config: %v, using command line flags and environment variables", err)
  133. }
  134. // 使用 Config 管理器初始化日志系统(自动处理优先级)
  135. if err = config.InitLogFromConfig(); err != nil {
  136. log.WithError(err).Errorf("log init error.")
  137. }
  138. if err = rlimit.RemoveMemlock(); err != nil {
  139. log.WithError(err).Warning("Failed Removing memlock.")
  140. } else {
  141. log.Info("Rlimit removed")
  142. }
  143. //log.LogToStderr(false)
  144. //log.SetOutput(&RateLimitedLogOutput{limiter: rate.NewLimiter(rate.Limit(*flags.LogPerSecond), *flags.LogBurst)})
  145. log.Infoln("agent version:", version)
  146. if *flags.RunInContainer {
  147. _, err = kube.NewKubeClient()
  148. if err != nil {
  149. log.WithError(err).Errorf("Failed to init kube client.")
  150. }
  151. }
  152. hostname, kv, err := uname()
  153. if err != nil {
  154. log.Fatalln("failed to get uname:", err)
  155. }
  156. log.Infoln("hostname:", hostname)
  157. log.Infoln("kernel version:", kv)
  158. // 构建节点信息
  159. nodeInfo, err := node.NewNodeInfo(hostname, kv, version)
  160. if err != nil || nodeInfo == nil {
  161. log.Fatalln(err)
  162. }
  163. log.Infof("node info %s", utils.ToString(nodeInfo))
  164. ver := common.KernelMajorMinor(kv)
  165. if ver == "" {
  166. log.Fatalln("invalid kernel version:", kv)
  167. }
  168. if semver.Compare("v"+ver, "v"+minSupportedKernelVersion) == -1 {
  169. log.Fatalf("the minimum Linux kernel version required is %s or later", minSupportedKernelVersion)
  170. }
  171. whitelistNodeExternalNetworks()
  172. SystemUUID := nodeInfo.GetNodeInfo().SystemUUID
  173. tracing.Init(SystemUUID, hostname, version)
  174. logs.Init(SystemUUID, hostname, version)
  175. registry := prometheus.NewRegistry()
  176. registerer := prometheus.WrapRegistererWith(prometheus.Labels{"system_uuid": SystemUUID}, registry)
  177. registerer.MustRegister(info("node_agent_info", version))
  178. if err := registerer.Register(node.NewCollector(hostname, kv)); err != nil {
  179. log.Fatalln(err)
  180. }
  181. //processInfoCh := profiling.Init(machineId, hostname)
  182. cr, err := containers.NewRegistry(registerer, kv, nodeInfo, nil)
  183. if err != nil {
  184. log.Fatalln(err)
  185. }
  186. //defer cr.Close()
  187. log.Infoln("START_TRACE")
  188. if *flags.RunInOmniagent {
  189. //namedpipe初始化
  190. npCtl, err := namedpipe.NewNamedPipeCtl(nil)
  191. if err != nil {
  192. log.Errorf("get namedpipeCtl occurs error: %s", err.Error())
  193. } else {
  194. //监听&处理-熔断信号
  195. npCtl.AcceptAndDisposeMsg(cr)
  196. }
  197. }
  198. //heartbeat
  199. try.GoParams(containers.DoHeartbeat, utils.CatchFn, filepath.Join(utils.GetRootPath(), "heartbeat"))
  200. //profiling.Start()
  201. //defer profiling.Stop()
  202. // 创建一个/metrics路由处理函数
  203. sendNetDataDone := make(chan struct{})
  204. if *flags.SendNetData {
  205. sendNetDataFunc := func() {
  206. // 从注册表中获取指标数据
  207. metrics, err := registry.Gather()
  208. if err != nil {
  209. // 错误处理
  210. return
  211. }
  212. // 创建正则表达式对象
  213. // regex, err := regexp.Compile(`^process_.+_queries_total$`)
  214. // if err != nil {
  215. // return
  216. // }
  217. var postData PostData
  218. postData.AccountID = strconv.Itoa(nodeInfo.AccountID)
  219. postData.IP = nodeInfo.HostIp
  220. postData.HostID = nodeInfo.HostID
  221. postData.TimeStamp = uint64(time.Now().UnixNano())
  222. postData.ServiceType = 30002
  223. postData.HostName = nodeInfo.Hostname
  224. for _, metric := range metrics {
  225. if metric.GetName() != "process_net_tcp_successful_connects_total" &&
  226. metric.GetName() != "process_net_tcp_failed_connects_total" &&
  227. metric.GetName() != "process_net_tcp_retransmits_total" &&
  228. metric.GetName() != "process_net_tcp_listen_info" &&
  229. metric.GetName() != "process_http_requests_total" &&
  230. metric.GetName() != "process_http_requests_duration_seconds_total" &&
  231. metric.GetName() != "process_http_requests_duration_seconds_total_count" &&
  232. metric.GetName() != "process_mysql_queries_total" &&
  233. metric.GetName() != "process_mysql_queries_duration_seconds_total" &&
  234. // metric.GetName() != "process_mysql_queries_duration_seconds_total_count" &&
  235. metric.GetName() != "process_redis_queries_total" &&
  236. metric.GetName() != "process_redis_queries_duration_seconds_total" &&
  237. // metric.GetName() != "process_redis_queries_duration_seconds_total_count" &&
  238. metric.GetName() != "process_postgres_queries_total" &&
  239. metric.GetName() != "process_postgres_queries_duration_seconds_total" &&
  240. // metric.GetName() != "process_postgres_queries_duration_seconds_total_count" &&
  241. // regex.MatchString(metric.GetName()) == false &&
  242. metric.GetName() != "process_dm_queries_total" &&
  243. metric.GetName() != "process_dm_queries_duration_seconds_total" &&
  244. metric.GetName() != "process_application_type" &&
  245. metric.GetName() != "process_net_tcp_bytes_received_per" &&
  246. metric.GetName() != "process_net_tcp_bytes_sent_per" &&
  247. metric.GetName() != "process_net_tcp_bytes_received_total" &&
  248. metric.GetName() != "process_net_tcp_bytes_sent_total" &&
  249. metric.GetName() != "process_net_tcp_data_latency_time" &&
  250. metric.GetName() != "process_net_tcp_flow_duration_time" &&
  251. metric.GetName() != "process_net_tcp_connection_establish_time" {
  252. continue
  253. }
  254. var item MetricData
  255. var itemOther MetricData
  256. item.MetricKey = metric.GetName()
  257. for _, m := range metric.GetMetric() {
  258. metricItem := MetricItemData{}
  259. label := make(map[string]string)
  260. for _, l := range m.GetLabel() {
  261. label[l.GetName()] = l.GetValue()
  262. }
  263. metricItem.Label = label
  264. switch metric.GetType() {
  265. case dto.MetricType_COUNTER:
  266. metricItem.Value = m.GetCounter().GetValue()
  267. item.Metric = append(item.Metric, metricItem)
  268. case dto.MetricType_GAUGE:
  269. metricItem.Value = m.GetGauge().GetValue()
  270. item.Metric = append(item.Metric, metricItem)
  271. case dto.MetricType_HISTOGRAM:
  272. item.MetricKey = metric.GetName() + "_sum"
  273. metricItem.Value = m.GetHistogram().GetSampleSum()
  274. item.Metric = append(item.Metric, metricItem)
  275. metricItemOther := MetricItemData{}
  276. metricItemOther.Label = label
  277. itemOther.MetricKey = metric.GetName() + "_count"
  278. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  279. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  280. default:
  281. continue
  282. }
  283. }
  284. postData.Data = append(postData.Data, item)
  285. if metric.GetType() == dto.MetricType_HISTOGRAM {
  286. postData.Data = append(postData.Data, itemOther)
  287. }
  288. }
  289. // 将指标数据转换为JSON格式
  290. jsonData, err := json.Marshal(postData)
  291. //jsonData, err := json.Marshal(metrics)
  292. if err != nil {
  293. return
  294. }
  295. // log.Debugln("netdata is:", string(jsonData))
  296. // 创建请求
  297. urlRoute := "/api/v2/ebpf/receive"
  298. log.Infoln("send url is ", *flags.DataServer+*flags.ServerPrefix+urlRoute)
  299. // req, err := http.NewRequest("POST", "http://10.0.7.115:18080/api/v2/ebpf/receive", bytes.NewBuffer(jsonData))
  300. req, err := http.NewRequest("POST", *flags.DataServer+*flags.ServerPrefix+urlRoute, bytes.NewBuffer(jsonData))
  301. if err != nil {
  302. log.Errorf(err.Error())
  303. return
  304. }
  305. // 添加 Content-Type header
  306. req.Header.Add("Content-Type", "application/json")
  307. // 添加一个自定义 header
  308. req.Header.Add("DataCount", strconv.Itoa(len(postData.Data)))
  309. req.Header.Add("Account-Id", strconv.Itoa(nodeInfo.AccountID))
  310. req.Header.Add("ip", nodeInfo.HostIp)
  311. // 创建 HTTP 客户端
  312. client := &http.Client{}
  313. // 发送 HTTP POST 请求
  314. response, err := client.Do(req)
  315. if err != nil {
  316. log.Errorf(err.Error())
  317. return
  318. }
  319. defer response.Body.Close()
  320. // 读取响应内容
  321. responseData, err := io.ReadAll(response.Body)
  322. if err != nil {
  323. log.Infoln("Error:", err)
  324. return
  325. }
  326. // 输出响应状态码和响应正文
  327. log.Infoln("Status Code:", response.StatusCode)
  328. log.Infoln("Response Body:", string(responseData))
  329. }
  330. try.Go(func() {
  331. sendNetDataTicker := time.NewTicker(sendNetDataInterval)
  332. defer sendNetDataTicker.Stop()
  333. for {
  334. select {
  335. case <-sendNetDataDone:
  336. return
  337. case _ = <-sendNetDataTicker.C:
  338. log.Infoln("before enter sendNetDataFunc")
  339. if !cr.IsFusing() {
  340. log.Infoln("after enter sendNetDataFunc")
  341. sendNetDataFunc()
  342. }
  343. }
  344. }
  345. }, utils.CatchFn)
  346. }
  347. /* metricsHandler := func(w http.ResponseWriter, r *http.Request) {
  348. // 从注册表中获取指标数据
  349. metrics, err := registry.Gather()
  350. if err != nil {
  351. // 错误处理
  352. http.Error(w, err.Error(), http.StatusInternalServerError)
  353. return
  354. }
  355. // 创建正则表达式对象
  356. // regex, err := regexp.Compile(`^process_.+_queries_total$`)
  357. // if err != nil {
  358. // return
  359. // }
  360. var postData PostData
  361. postData.AccountID = strconv.Itoa(nodeInfo.AccountID)
  362. postData.IP = nodeInfo.HostIp
  363. postData.HostID = nodeInfo.HostID
  364. postData.TimeStamp = uint64(time.Now().UnixNano())
  365. postData.ServiceType = 30002
  366. postData.HostName = nodeInfo.Hostname
  367. for _, metric := range metrics {
  368. if metric.GetName() != "process_net_tcp_successful_connects_total" &&
  369. metric.GetName() != "process_net_tcp_failed_connects_total" &&
  370. metric.GetName() != "process_net_tcp_retransmits_total" &&
  371. metric.GetName() != "process_net_tcp_listen_info" &&
  372. metric.GetName() != "process_http_requests_total" &&
  373. metric.GetName() != "process_http_requests_duration_seconds_total" &&
  374. metric.GetName() != "process_http_requests_duration_seconds_total_count" &&
  375. metric.GetName() != "process_mysql_queries_total" &&
  376. metric.GetName() != "process_mysql_queries_duration_seconds_total" &&
  377. // metric.GetName() != "process_mysql_queries_duration_seconds_total_count" &&
  378. metric.GetName() != "process_redis_queries_total" &&
  379. metric.GetName() != "process_redis_queries_duration_seconds_total" &&
  380. // metric.GetName() != "process_redis_queries_duration_seconds_total_count" &&
  381. metric.GetName() != "process_postgres_queries_total" &&
  382. metric.GetName() != "process_postgres_queries_duration_seconds_total" &&
  383. // metric.GetName() != "process_postgres_queries_duration_seconds_total_count" &&
  384. // regex.MatchString(metric.GetName()) == false &&
  385. metric.GetName() != "process_dm_queries_total" &&
  386. metric.GetName() != "process_dm_queries_duration_seconds_total" &&
  387. metric.GetName() != "process_application_type" &&
  388. metric.GetName() != "process_net_tcp_bytes_received_per" &&
  389. metric.GetName() != "process_net_tcp_bytes_sent_per" &&
  390. metric.GetName() != "process_net_tcp_bytes_received_total" &&
  391. metric.GetName() != "process_net_tcp_bytes_sent_total" &&
  392. metric.GetName() != "process_net_tcp_data_latency_time" &&
  393. metric.GetName() != "process_net_tcp_flow_duration_time" &&
  394. metric.GetName() != "process_net_tcp_connection_establish_time" {
  395. continue
  396. }
  397. var item MetricData
  398. var itemOther MetricData
  399. item.MetricKey = metric.GetName()
  400. for _, m := range metric.GetMetric() {
  401. metricItem := MetricItemData{}
  402. label := make(map[string]string)
  403. for _, l := range m.GetLabel() {
  404. label[l.GetName()] = l.GetValue()
  405. }
  406. metricItem.Label = label
  407. switch metric.GetType() {
  408. case dto.MetricType_COUNTER:
  409. metricItem.Value = m.GetCounter().GetValue()
  410. item.Metric = append(item.Metric, metricItem)
  411. case dto.MetricType_GAUGE:
  412. metricItem.Value = m.GetGauge().GetValue()
  413. item.Metric = append(item.Metric, metricItem)
  414. case dto.MetricType_HISTOGRAM:
  415. item.MetricKey = metric.GetName() + "_sum"
  416. metricItem.Value = m.GetHistogram().GetSampleSum()
  417. item.Metric = append(item.Metric, metricItem)
  418. metricItemOther := MetricItemData{}
  419. metricItemOther.Label = label
  420. itemOther.MetricKey = metric.GetName() + "_count"
  421. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  422. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  423. default:
  424. continue
  425. }
  426. }
  427. postData.Data = append(postData.Data, item)
  428. if metric.GetType() == dto.MetricType_HISTOGRAM {
  429. postData.Data = append(postData.Data, itemOther)
  430. }
  431. }
  432. // 将指标数据转换为JSON格式
  433. jsonData, err := json.Marshal(postData)
  434. //jsonData, err := json.Marshal(metrics)
  435. if err != nil {
  436. http.Error(w, err.Error(), http.StatusInternalServerError)
  437. return
  438. }
  439. w.Header().Set("Content-Type", "application/json")
  440. w.Write(jsonData)
  441. // 创建请求
  442. req, err := http.NewRequest("POST", "http://10.0.7.115:18080/api/v2/ebpf/receive", bytes.NewBuffer(jsonData))
  443. if err != nil {
  444. log.Errorf("Error:", err)
  445. return
  446. }
  447. // 添加 Content-Type header
  448. req.Header.Add("Content-Type", "application/json")
  449. // 添加一个自定义 header
  450. req.Header.Add("DataCount", strconv.Itoa(len(postData.Data)))
  451. req.Header.Add("Account-Id", strconv.Itoa(nodeInfo.AccountID))
  452. req.Header.Add("ip", nodeInfo.HostIp)
  453. // 创建 HTTP 客户端
  454. client := &http.Client{}
  455. // 发送 HTTP POST 请求
  456. response, err := client.Do(req)
  457. if err != nil {
  458. log.Errorf("Error:", err)
  459. return
  460. }
  461. defer response.Body.Close()
  462. // 读取响应内容
  463. responseData, err := io.ReadAll(response.Body)
  464. if err != nil {
  465. log.Errorf("Error:", err)
  466. return
  467. }
  468. // 输出响应状态码和响应正文
  469. log.Debugln("Status Code:", response.StatusCode)
  470. log.Infoln("Response Body:", string(responseData))
  471. }*/
  472. /*if err := prom.StartAgent(SystemUUID); err != nil {
  473. log.Fatalln(err)
  474. }
  475. http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: logger{}, Registry: registerer}))
  476. http.HandleFunc("/metrics2", metricsHandler)
  477. log.Infoln("listening on:", *flags.ListenAddress)
  478. log.Errorln(http.ListenAndServe(*flags.ListenAddress, nil))*/
  479. sigs := make(chan os.Signal, 1)
  480. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
  481. done := make(chan struct{})
  482. try.Go(func() {
  483. <-sigs
  484. log.Infoln("Signal received, shutting down...")
  485. cr.Close()
  486. close(sendNetDataDone)
  487. close(done)
  488. }, utils.CatchFn)
  489. select {
  490. case <-done:
  491. log.Infoln(flags.AgentName + " exited successfully.")
  492. }
  493. }
  494. func info(name, version string) prometheus.Collector {
  495. g := prometheus.NewGauge(prometheus.GaugeOpts{
  496. Name: name,
  497. ConstLabels: prometheus.Labels{"version": version},
  498. })
  499. g.Set(1)
  500. return g
  501. }
  502. type logger struct{}
  503. func (l logger) Println(v ...interface{}) {
  504. log.Errorln(v...)
  505. }
  506. type RateLimitedLogOutput struct {
  507. limiter *rate.Limiter
  508. }
  509. func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
  510. if !o.limiter.Allow() {
  511. return len(data), nil
  512. }
  513. return os.Stderr.Write(data)
  514. }