main.go 19 KB

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