main.go 10 KB

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