main.go 12 KB

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