main.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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. urlRoute := "/api/v2/ebpf/receive"
  303. log.Infoln("send url is ", config.Cfg.GetString("dataServer")+*flags.ServerPrefix+urlRoute)
  304. // req, err := http.NewRequest("POST", "http://10.0.7.115:18080/api/v2/ebpf/receive", bytes.NewBuffer(jsonData))
  305. req, err := http.NewRequest("POST", config.Cfg.GetString("dataServer")+*flags.ServerPrefix+urlRoute, bytes.NewBuffer(jsonData))
  306. if err != nil {
  307. log.Errorf(err.Error())
  308. return
  309. }
  310. // 添加 Content-Type header
  311. req.Header.Add("Content-Type", "application/json")
  312. // 添加一个自定义 header
  313. req.Header.Add("DataCount", strconv.Itoa(len(postData.Data)))
  314. req.Header.Add("Account-Id", strconv.Itoa(nodeInfo.AccountID))
  315. req.Header.Add("ip", nodeInfo.HostIp)
  316. // 创建 HTTP 客户端
  317. client := &http.Client{}
  318. // 发送 HTTP POST 请求
  319. response, err := client.Do(req)
  320. if err != nil {
  321. log.Errorf(err.Error())
  322. return
  323. }
  324. defer response.Body.Close()
  325. // 读取响应内容
  326. responseData, err := io.ReadAll(response.Body)
  327. if err != nil {
  328. log.Infoln("Error:", err)
  329. return
  330. }
  331. // 输出响应状态码和响应正文
  332. log.Infoln("Status Code:", response.StatusCode)
  333. log.Infoln("Response Body:", string(responseData))
  334. }
  335. sendNetDataDone := make(chan struct{})
  336. try.Go(func() {
  337. intervalChangeCh := config.Cfg.SubscribeConfigChange(config.ScbTypeNetDataIntervalChg)
  338. dataServerChangeCh := config.Cfg.SubscribeConfigChange(config.ScbTypeDataServerChg)
  339. interval := time.Duration(config.Cfg.GetInt("netDataInterval")) * time.Minute
  340. sendNetDataTicker := time.NewTicker(interval)
  341. defer sendNetDataTicker.Stop()
  342. for {
  343. select {
  344. case <-sendNetDataDone:
  345. return
  346. case _ = <-sendNetDataTicker.C:
  347. log.Infoln("before enter sendNetDataFunc")
  348. if !cr.IsFusing() {
  349. log.Infoln("after enter sendNetDataFunc")
  350. sendNetDataFunc()
  351. }
  352. case _, ok := <-intervalChangeCh:
  353. if ok {
  354. log.Infof("the configuration `netDataInterval` changed,new netDataInterval [%d]", config.Cfg.GetInt("netDataInterval"))
  355. interval = time.Duration(config.Cfg.GetInt("netDataInterval")) * time.Minute
  356. sendNetDataTicker.Reset(interval)
  357. log.Infof("the configuration `netDataInterval` change finished")
  358. } else {
  359. intervalChangeCh = nil
  360. log.Infof("SubscribeConfigChange ScbTypeNetDataIntervalChg exit")
  361. }
  362. case _, ok := <-dataServerChangeCh:
  363. if ok {
  364. // something todo?
  365. log.Infof("the configuration `dataServer` changed,new dataServer [%s]", config.Cfg.GetString("dataServer"))
  366. } else {
  367. dataServerChangeCh = nil
  368. log.Infof("SubscribeConfigChange ScbTypeDataServerChg exit")
  369. }
  370. }
  371. }
  372. }, utils.CatchFn)
  373. /* metricsHandler := func(w http.ResponseWriter, r *http.Request) {
  374. // 从注册表中获取指标数据
  375. metrics, err := registry.Gather()
  376. if err != nil {
  377. // 错误处理
  378. http.Error(w, err.Error(), http.StatusInternalServerError)
  379. return
  380. }
  381. // 创建正则表达式对象
  382. // regex, err := regexp.Compile(`^process_.+_queries_total$`)
  383. // if err != nil {
  384. // return
  385. // }
  386. var postData PostData
  387. postData.AccountID = strconv.Itoa(nodeInfo.AccountID)
  388. postData.IP = nodeInfo.HostIp
  389. postData.HostID = nodeInfo.HostID
  390. postData.TimeStamp = uint64(time.Now().UnixNano())
  391. postData.ServiceType = 30002
  392. postData.HostName = nodeInfo.Hostname
  393. for _, metric := range metrics {
  394. if metric.GetName() != "process_net_tcp_successful_connects_total" &&
  395. metric.GetName() != "process_net_tcp_failed_connects_total" &&
  396. metric.GetName() != "process_net_tcp_retransmits_total" &&
  397. metric.GetName() != "process_net_tcp_listen_info" &&
  398. metric.GetName() != "process_http_requests_total" &&
  399. metric.GetName() != "process_http_requests_duration_seconds_total" &&
  400. metric.GetName() != "process_http_requests_duration_seconds_total_count" &&
  401. metric.GetName() != "process_mysql_queries_total" &&
  402. metric.GetName() != "process_mysql_queries_duration_seconds_total" &&
  403. // metric.GetName() != "process_mysql_queries_duration_seconds_total_count" &&
  404. metric.GetName() != "process_redis_queries_total" &&
  405. metric.GetName() != "process_redis_queries_duration_seconds_total" &&
  406. // metric.GetName() != "process_redis_queries_duration_seconds_total_count" &&
  407. metric.GetName() != "process_postgres_queries_total" &&
  408. metric.GetName() != "process_postgres_queries_duration_seconds_total" &&
  409. // metric.GetName() != "process_postgres_queries_duration_seconds_total_count" &&
  410. // regex.MatchString(metric.GetName()) == false &&
  411. metric.GetName() != "process_dm_queries_total" &&
  412. metric.GetName() != "process_dm_queries_duration_seconds_total" &&
  413. metric.GetName() != "process_application_type" &&
  414. metric.GetName() != "process_net_tcp_bytes_received_per" &&
  415. metric.GetName() != "process_net_tcp_bytes_sent_per" &&
  416. metric.GetName() != "process_net_tcp_bytes_received_total" &&
  417. metric.GetName() != "process_net_tcp_bytes_sent_total" &&
  418. metric.GetName() != "process_net_tcp_data_latency_time" &&
  419. metric.GetName() != "process_net_tcp_flow_duration_time" &&
  420. metric.GetName() != "process_net_tcp_connection_establish_time" {
  421. continue
  422. }
  423. var item MetricData
  424. var itemOther MetricData
  425. item.MetricKey = metric.GetName()
  426. for _, m := range metric.GetMetric() {
  427. metricItem := MetricItemData{}
  428. label := make(map[string]string)
  429. for _, l := range m.GetLabel() {
  430. label[l.GetName()] = l.GetValue()
  431. }
  432. metricItem.Label = label
  433. switch metric.GetType() {
  434. case dto.MetricType_COUNTER:
  435. metricItem.Value = m.GetCounter().GetValue()
  436. item.Metric = append(item.Metric, metricItem)
  437. case dto.MetricType_GAUGE:
  438. metricItem.Value = m.GetGauge().GetValue()
  439. item.Metric = append(item.Metric, metricItem)
  440. case dto.MetricType_HISTOGRAM:
  441. item.MetricKey = metric.GetName() + "_sum"
  442. metricItem.Value = m.GetHistogram().GetSampleSum()
  443. item.Metric = append(item.Metric, metricItem)
  444. metricItemOther := MetricItemData{}
  445. metricItemOther.Label = label
  446. itemOther.MetricKey = metric.GetName() + "_count"
  447. metricItemOther.Value = m.GetHistogram().GetSampleCount()
  448. itemOther.Metric = append(itemOther.Metric, metricItemOther)
  449. default:
  450. continue
  451. }
  452. }
  453. postData.Data = append(postData.Data, item)
  454. if metric.GetType() == dto.MetricType_HISTOGRAM {
  455. postData.Data = append(postData.Data, itemOther)
  456. }
  457. }
  458. // 将指标数据转换为JSON格式
  459. jsonData, err := json.Marshal(postData)
  460. //jsonData, err := json.Marshal(metrics)
  461. if err != nil {
  462. http.Error(w, err.Error(), http.StatusInternalServerError)
  463. return
  464. }
  465. w.Header().Set("Content-Type", "application/json")
  466. w.Write(jsonData)
  467. // 创建请求
  468. req, err := http.NewRequest("POST", "http://10.0.7.115:18080/api/v2/ebpf/receive", bytes.NewBuffer(jsonData))
  469. if err != nil {
  470. log.Errorf("Error:", err)
  471. return
  472. }
  473. // 添加 Content-Type header
  474. req.Header.Add("Content-Type", "application/json")
  475. // 添加一个自定义 header
  476. req.Header.Add("DataCount", strconv.Itoa(len(postData.Data)))
  477. req.Header.Add("Account-Id", strconv.Itoa(nodeInfo.AccountID))
  478. req.Header.Add("ip", nodeInfo.HostIp)
  479. // 创建 HTTP 客户端
  480. client := &http.Client{}
  481. // 发送 HTTP POST 请求
  482. response, err := client.Do(req)
  483. if err != nil {
  484. log.Errorf("Error:", err)
  485. return
  486. }
  487. defer response.Body.Close()
  488. // 读取响应内容
  489. responseData, err := io.ReadAll(response.Body)
  490. if err != nil {
  491. log.Errorf("Error:", err)
  492. return
  493. }
  494. // 输出响应状态码和响应正文
  495. log.Debugln("Status Code:", response.StatusCode)
  496. log.Infoln("Response Body:", string(responseData))
  497. }*/
  498. /*if err := prom.StartAgent(SystemUUID); err != nil {
  499. log.Fatalln(err)
  500. }
  501. http.Handle("/metrics", promhttp.HandlerFor(registry, promhttp.HandlerOpts{ErrorLog: logger{}, Registry: registerer}))
  502. http.HandleFunc("/metrics2", metricsHandler)
  503. log.Infoln("listening on:", *flags.ListenAddress)
  504. log.Errorln(http.ListenAndServe(*flags.ListenAddress, nil))*/
  505. sigs := make(chan os.Signal, 1)
  506. signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
  507. done := make(chan struct{})
  508. try.Go(func() {
  509. <-sigs
  510. log.Infoln("Signal received, shutting down...")
  511. cr.Close()
  512. config.Cfg.Close()
  513. close(sendNetDataDone)
  514. close(done)
  515. }, utils.CatchFn)
  516. select {
  517. case <-done:
  518. log.Infoln(flags.AgentName + " exited successfully.")
  519. }
  520. }
  521. func info(name, version string) prometheus.Collector {
  522. g := prometheus.NewGauge(prometheus.GaugeOpts{
  523. Name: name,
  524. ConstLabels: prometheus.Labels{"version": version},
  525. })
  526. g.Set(1)
  527. return g
  528. }
  529. type logger struct{}
  530. func (l logger) Println(v ...interface{}) {
  531. log.Errorln(v...)
  532. }
  533. type RateLimitedLogOutput struct {
  534. limiter *rate.Limiter
  535. }
  536. func (o *RateLimitedLogOutput) Write(data []byte) (int, error) {
  537. if !o.limiter.Allow() {
  538. return len(data), nil
  539. }
  540. return os.Stderr.Write(data)
  541. }