main.go 11 KB

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