registry.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709
  1. package containers
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/coroot/coroot-node-agent/kube"
  12. . "github.com/coroot/coroot-node-agent/utils"
  13. "github.com/coroot/coroot-node-agent/utils/enums"
  14. . "github.com/coroot/coroot-node-agent/utils/modelse"
  15. "github.com/coroot/coroot-node-agent/utils/try"
  16. . "github.com/coroot/coroot-node-agent/utils/worker"
  17. "github.com/coroot/coroot-node-agent/cgroup"
  18. "github.com/coroot/coroot-node-agent/common"
  19. "github.com/coroot/coroot-node-agent/ebpftracer"
  20. "github.com/coroot/coroot-node-agent/ebpftracer/tracer"
  21. "github.com/coroot/coroot-node-agent/flags"
  22. "github.com/coroot/coroot-node-agent/proc"
  23. "github.com/prometheus/client_golang/prometheus"
  24. klog "github.com/sirupsen/logrus"
  25. "github.com/vishvananda/netns"
  26. "inet.af/netaddr"
  27. )
  28. const MinTrafficStatsUpdateInterval = 5 * time.Second
  29. var (
  30. selfNetNs = netns.None()
  31. hostNetNsId = netns.None().UniqueId()
  32. agentPid = uint32(os.Getpid())
  33. containerIdRegexp = regexp.MustCompile(`[a-z0-9]{64}`)
  34. cronjobPodName = regexp.MustCompile(`([a-z0-9-]+)-([0-9]{8})-[bcdfghjklmnpqrstvwxz2456789]{5}`)
  35. cronjobPodScheduleWindow = 7 * 24 * time.Hour
  36. )
  37. type ProcessInfo struct {
  38. Pid uint32
  39. ContainerId ContainerID
  40. StartedAt time.Time
  41. }
  42. type Registry struct {
  43. reg prometheus.Registerer
  44. tracer *ebpftracer.Tracer
  45. events chan ebpftracer.Event
  46. hostConntrack *Conntrack
  47. containersById map[ContainerID]*Container
  48. containersByCgroupId map[string]*Container
  49. containersByPid map[uint32]*Container
  50. ip2fqdn map[netaddr.IP]string
  51. ip2fqdnLock sync.Mutex
  52. processInfoCh chan<- ProcessInfo
  53. whiteListRules WhiteListMap
  54. whiteLastUpdatedTime int
  55. connServer ServerWorker
  56. trafficStatsLastUpdated time.Time
  57. trafficStatsLock sync.Mutex
  58. trafficStatsUpdateCh chan *TrafficStatsUpdate
  59. nodeInfo *NodeInfoT
  60. }
  61. var (
  62. uprobes []tracer.Uprobe
  63. uprobesMap map[string]tracer.Uprobe
  64. )
  65. func NewRegistry(reg prometheus.Registerer, kernelVersion string, nodeInfo *NodeInfoT, processInfoCh chan<- ProcessInfo) (*Registry, error) {
  66. ns, err := proc.GetSelfNetNs()
  67. if err != nil {
  68. return nil, err
  69. }
  70. selfNetNs = ns
  71. hostNetNs, err := proc.GetHostNetNs()
  72. if err != nil {
  73. return nil, err
  74. }
  75. defer hostNetNs.Close()
  76. hostNetNsId = hostNetNs.UniqueId()
  77. err = proc.ExecuteInNetNs(hostNetNs, selfNetNs, func() error {
  78. if err := TaskstatsInit(); err != nil {
  79. return err
  80. }
  81. return nil
  82. })
  83. if err != nil {
  84. return nil, err
  85. }
  86. if err := cgroup.Init(); err != nil {
  87. return nil, err
  88. }
  89. if err := DockerdInit(); err != nil {
  90. klog.Warningln(err)
  91. }
  92. if err := ContainerdInit(); err != nil {
  93. klog.Warningln(err)
  94. }
  95. if err := CrioInit(); err != nil {
  96. klog.Warningln(err)
  97. }
  98. if err := JournaldInit(); err != nil {
  99. klog.Warningln(err)
  100. }
  101. ct, err := NewConntrack(hostNetNs)
  102. if err != nil {
  103. return nil, err
  104. }
  105. r := &Registry{
  106. reg: reg,
  107. events: make(chan ebpftracer.Event, 10000),
  108. hostConntrack: ct,
  109. containersById: map[ContainerID]*Container{},
  110. containersByCgroupId: map[string]*Container{},
  111. containersByPid: map[uint32]*Container{},
  112. ip2fqdn: map[netaddr.IP]string{},
  113. processInfoCh: processInfoCh,
  114. tracer: ebpftracer.NewTracer(kernelVersion, *flags.DisableL7Tracing, *flags.DisableE2ETracing, *flags.DisableStackTracing),
  115. whiteListRules: make(WhiteListMap),
  116. trafficStatsUpdateCh: make(chan *TrafficStatsUpdate),
  117. nodeInfo: nodeInfo,
  118. }
  119. // 初始化软负载集群节点
  120. proxyClient, clientErr := NewProxyClient(*flags.ConfigServer, false)
  121. if clientErr == nil {
  122. // 负载健康检测
  123. try.Go(proxyClient.CheckEndpoints, CatchFn)
  124. log.Infof("New Proxy Client success.config_server is [%s]", *flags.ConfigServer)
  125. } else {
  126. klog.WithError(clientErr).Errorf("NewProxyClient error, Please check [export CONFIG_ENDPOINT=ip:port]")
  127. return nil, clientErr
  128. }
  129. r.connServer, err = NewServerHTTPWorker()
  130. if err != nil {
  131. klog.Errorf("init connServer error:%s.", err)
  132. return nil, err
  133. }
  134. if !*flags.DisableRegisterHost {
  135. // Register Host
  136. err = r.RegisterHost()
  137. if err != nil {
  138. klog.WithError(err).Errorf("Failed Register Host.")
  139. return nil, err
  140. }
  141. }
  142. if err = reg.Register(r); err != nil {
  143. return nil, err
  144. }
  145. //_, err = r.getWhiteList()
  146. //if err != nil {
  147. // return nil, err
  148. //}
  149. go r.handleEvents(r.events)
  150. if err = r.tracer.Run(r.events); err != nil {
  151. close(r.events)
  152. return nil, err
  153. }
  154. return r, nil
  155. }
  156. func (r *Registry) Describe(ch chan<- *prometheus.Desc) {
  157. ch <- metrics.Ip2Fqdn
  158. }
  159. func (r *Registry) Collect(ch chan<- prometheus.Metric) {
  160. r.ip2fqdnLock.Lock()
  161. defer r.ip2fqdnLock.Unlock()
  162. for ip, fqdn := range r.ip2fqdn {
  163. ch <- gauge(metrics.Ip2Fqdn, 1, ip.String(), fqdn)
  164. }
  165. }
  166. func (r *Registry) Close() {
  167. r.tracer.Close()
  168. close(r.events)
  169. }
  170. func (r *Registry) handleEvents(ch <-chan ebpftracer.Event) {
  171. gcTicker := time.NewTicker(gcInterval)
  172. defer gcTicker.Stop()
  173. for {
  174. select {
  175. case now := <-gcTicker.C:
  176. _, err := r.getWhiteList()
  177. if err != nil {
  178. klog.WithError(err).Errorf("connWhiteList error")
  179. }
  180. runtimeApps := make(map[uint32]AppStatusInfo)
  181. for pid, c := range r.containersByPid {
  182. if c != nil {
  183. if c != nil && !common.IsOpenFilter() {
  184. verifyAttachConditions := c.verifyAttachConditions(r, pid)
  185. if verifyAttachConditions {
  186. err = c.RegisterAppInfo(r, pid)
  187. if err == nil {
  188. klog.WithField("pid", pid).Infoln("[registry] Attach uprobes.")
  189. err = c.attachUprobes(r.tracer, pid)
  190. if err != nil {
  191. klog.WithField("pid", pid).WithError(err).Errorf("[registry] Failed attach uprobes error!")
  192. } else {
  193. klog.WithField("pid", pid).Infoln("[registry] Attach uprobes success!")
  194. }
  195. klog.WithField("pid", pid).Infoln("[registry] Attach app stack.")
  196. err = c.StackTrace(r.tracer, pid)
  197. if err != nil {
  198. klog.WithField("pid", pid).WithError(err).Errorf("[registry][end] Failed attach stack trace!")
  199. }
  200. } else {
  201. klog.WithError(err).Errorf("[registry] Failed registerAppInfo.")
  202. }
  203. }
  204. if !verifyAttachConditions && c.checkL7AttachReady() {
  205. // detach
  206. c.detachUprobes(pid)
  207. }
  208. }
  209. if c.AppInfo.AppName != "" {
  210. detail := AppStatusInfo{
  211. Pid: pid,
  212. ProcName: c.containerName,
  213. AppName: c.AppInfo.AppName,
  214. Language: c.AppInfo.CodeType.String(),
  215. AppID: c.AppInfo.AppIdHash.IntVal,
  216. AgentID: c.AppInfo.AgentId,
  217. InstanceID: c.AppInfo.InstanceIdHash.IntVal,
  218. Sn: c.AppInfo.Sn,
  219. Sport: c.AppInfo.Sport,
  220. RegisterAt: time.Unix(c.AppInfo.RegisterAt, 0).Format("060102 15:04:05"),
  221. Status: c.AppInfo.Status,
  222. }
  223. if c.AppInfo.UpdateAt != 0 {
  224. detail.UpdateAt = time.Unix(c.AppInfo.UpdateAt, 0).Format("060102 15:04:05")
  225. }
  226. runtimeApps[pid] = detail
  227. }
  228. }
  229. cg, err := proc.ReadCgroup(pid)
  230. if err != nil {
  231. delete(r.containersByPid, pid)
  232. if c != nil {
  233. c.onProcessExit(pid, false)
  234. }
  235. continue
  236. }
  237. if c != nil && cg.Id != c.cgroup.Id {
  238. delete(r.containersByPid, pid)
  239. c.onProcessExit(pid, false)
  240. }
  241. }
  242. saveAppInfo(runtimeApps)
  243. activeIPs := map[netaddr.IP]struct{}{}
  244. for id, c := range r.containersById {
  245. for dst := range c.connectLastAttempt {
  246. activeIPs[dst.IP()] = struct{}{}
  247. }
  248. if !c.Dead(now) {
  249. continue
  250. }
  251. klog.Infoln("deleting dead container:", id)
  252. for cg, cc := range r.containersByCgroupId {
  253. if cc == c {
  254. delete(r.containersByCgroupId, cg)
  255. }
  256. }
  257. for pid, cc := range r.containersByPid {
  258. if cc == c {
  259. delete(r.containersByPid, pid)
  260. }
  261. }
  262. if ok := prometheus.WrapRegistererWith(setLabels(string(id),
  263. c.K8sContainer.ns,
  264. c.K8sContainer.workload,
  265. c.K8sContainer.podName,
  266. c.K8sContainer.containerName,
  267. c.K8sContainer.pid), r.reg).Unregister(c); !ok {
  268. klog.Warningln("failed to unregister container:", id)
  269. }
  270. delete(r.containersById, id)
  271. c.Close()
  272. }
  273. r.ip2fqdnLock.Lock()
  274. for ip := range r.ip2fqdn {
  275. if _, ok := activeIPs[ip]; !ok {
  276. delete(r.ip2fqdn, ip)
  277. }
  278. }
  279. r.ip2fqdnLock.Unlock()
  280. case u := <-r.trafficStatsUpdateCh:
  281. if u == nil {
  282. continue
  283. }
  284. if c := r.containersByPid[u.Pid]; c != nil {
  285. c.updateTrafficStats(u)
  286. }
  287. case e, more := <-ch:
  288. if e.Pid == uint32(os.Getpid()) {
  289. continue
  290. }
  291. if !more {
  292. return
  293. }
  294. switch e.Type {
  295. case ebpftracer.EventTypeProcessStart:
  296. c, seen := r.containersByPid[e.Pid]
  297. switch { // possible pids wraparound + missed `process-exit` event
  298. case c == nil && seen: // ignored
  299. delete(r.containersByPid, e.Pid)
  300. case c != nil: // revalidating by cgroup
  301. cg, err := proc.ReadCgroup(e.Pid)
  302. if err != nil || cg.Id != c.cgroup.Id {
  303. delete(r.containersByPid, e.Pid)
  304. c.onProcessExit(e.Pid, false)
  305. }
  306. }
  307. if c := r.getOrCreateContainer(e.Pid); c != nil {
  308. p := c.onProcessStart(e.Pid)
  309. if r.processInfoCh != nil && p != nil {
  310. r.processInfoCh <- ProcessInfo{Pid: p.Pid, ContainerId: c.id, StartedAt: p.StartedAt}
  311. }
  312. }
  313. case ebpftracer.EventTypeProcessExit:
  314. if c := r.containersByPid[e.Pid]; c != nil {
  315. c.onProcessExit(e.Pid, e.Reason == ebpftracer.EventReasonOOMKill)
  316. }
  317. delete(r.containersByPid, e.Pid)
  318. case ebpftracer.EventTypeFileOpen:
  319. if c := r.getOrCreateContainer(e.Pid); c != nil {
  320. c.onFileOpen(e.Pid, e.Fd)
  321. }
  322. case ebpftracer.EventTypeListenOpen:
  323. //fmt.Println("ebpftracer.EventTypeListenOpen==================", e.Pid)
  324. if c := r.getOrCreateContainer(e.Pid); c != nil {
  325. c.onListenOpen(e.Pid, e.SrcAddr, false)
  326. // cmdline InstanceID agentID
  327. if c.buildIDs(e.Pid) {
  328. c.eventReady()
  329. }
  330. if common.IsOpenFilter() && common.IsFilterPid(e.Pid) {
  331. c.WhiteSettingInfo.AppName = enums.TestApp
  332. err := c.RegisterAppInfo(r, e.Pid)
  333. if err != nil {
  334. klog.WithError(err).Errorf("[registry] Failed registerAppInfo. pid is %d", e.Pid)
  335. continue
  336. }
  337. c.attachUprobes(r.tracer, e.Pid)
  338. err = c.StackTrace(r.tracer, e.Pid)
  339. if err != nil {
  340. klog.WithField("pid", e.Pid).WithError(err).Errorf("[registry][end] Failed attach stack trace!")
  341. }
  342. }
  343. } else {
  344. klog.Infoln("TCP listen open from unknown container", e)
  345. }
  346. case ebpftracer.EventTypeAcceptOpen:
  347. klog.Infoln("ebpftracer.EventTypeAcceptOpen==================", e.Pid)
  348. if c := r.getOrCreateContainer(e.Pid); c != nil {
  349. c.onAcceptOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false, e.Duration)
  350. c.eventReady()
  351. } else {
  352. klog.Infoln("TCP connection from unknown container", e)
  353. }
  354. case ebpftracer.EventTypeConnectionOpen:
  355. //fmt.Println("ebpftracer.EventTypeConnectionOpen==================", e.Pid)
  356. if c := r.getOrCreateContainer(e.Pid); c != nil {
  357. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false, e.Duration)
  358. if !c.checkEventReady() && c.buildIDs(e.Pid) {
  359. c.eventReady()
  360. }
  361. if common.IsOpenFilter() && common.IsFilterPid(e.Pid) {
  362. c.WhiteSettingInfo.AppName = enums.TestApp
  363. err := c.RegisterAppInfo(r, e.Pid)
  364. if err != nil {
  365. klog.WithError(err).Errorf("[registry] Failed registerAppInfo. pid is %d", e.Pid)
  366. continue
  367. }
  368. c.attachUprobes(r.tracer, e.Pid)
  369. err = c.StackTrace(r.tracer, e.Pid)
  370. if err != nil {
  371. klog.WithField("pid", e.Pid).WithError(err).Errorf("[registry][end] Failed attach stack trace!")
  372. }
  373. }
  374. } else {
  375. klog.Infoln("TCP connection from unknown container", e)
  376. }
  377. case ebpftracer.EventTypeListenClose:
  378. if c := r.containersByPid[e.Pid]; c != nil {
  379. c.onListenClose(e.Pid, e.SrcAddr)
  380. }
  381. case ebpftracer.EventTypeConnectionError:
  382. if c := r.getOrCreateContainer(e.Pid); c != nil {
  383. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, 0, true, e.Duration)
  384. } else {
  385. klog.Infoln("TCP connection error from unknown container", e)
  386. }
  387. case ebpftracer.EventTypeConnectionClose:
  388. if c := r.containersByPid[e.Pid]; c != nil {
  389. c.onConnectionClose(e)
  390. }
  391. case ebpftracer.EventTypeAcceptClose:
  392. if c := r.containersByPid[e.Pid]; c != nil {
  393. c.onAcceptClose(e)
  394. }
  395. case ebpftracer.EventTypeTCPRetransmit:
  396. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  397. for _, c := range r.containersById {
  398. if c.onRetransmission(srcDst) {
  399. break
  400. }
  401. }
  402. case ebpftracer.EventTypeL7Request:
  403. //fmt.Println("e.L7Request Payload:", string(e.L7Request.Payload))
  404. if e.L7Request == nil {
  405. continue
  406. }
  407. if c := r.containersByPid[e.Pid]; c != nil {
  408. //fmt.Println("EventTypeL7Request", e.Pid, c.checkL7AttachReady())
  409. //a, _ := json.Marshal(e.L7Request)
  410. //fmt.Println("EventTypeL7Request", e.Pid, string(a))
  411. fmt.Println("e---.L7Request Payload:", string(e.L7Request.Payload))
  412. ip2fqdn := c.onL7RequestApm(e.Pid, e.Fd, e.Timestamp, e.L7Request)
  413. r.ip2fqdnLock.Lock()
  414. for ip, fqdn := range ip2fqdn {
  415. r.ip2fqdn[ip] = fqdn
  416. }
  417. r.ip2fqdnLock.Unlock()
  418. }
  419. case ebpftracer.EventTypeFunEnt:
  420. if e.StackEvent == nil {
  421. continue
  422. }
  423. if c := r.containersByPid[uint32(e.StackEvent.Pid)]; c != nil {
  424. if e.StackEvent.Type == uint64(CodeTypeJava) {
  425. fmt.Printf("e.EventTypeFunEnt: TraceId:%d, Pid:%d, Location:%d, Goid:%d, TimeNs:%d, Ip:%X, CallerIp:%d, Bp:%d, CallerBp:%d\n", e.StackEvent.TraceId, e.StackEvent.Pid, e.StackEvent.Location, e.StackEvent.Goid, e.StackEvent.TimeNsStart, e.StackEvent.Ip, e.StackEvent.CallerIp, e.StackEvent.Bp, e.StackEvent.CallerBp)
  426. fmt.Printf("e.EventTypeFunEnt: TraceId: MethedName: %d -- %s -- %s", e.StackEvent.Type, e.StackEvent.MethedName, e.StackEvent.ClassName)
  427. } else {
  428. fmt.Printf("e.EventTypeFunEnt: TraceId:%d, Pid:%d, Location:%d, Goid:%d, TimeNs:%d, Ip:%X, CallerIp:%x, Bp:%x, CallerBp:%x\n", e.StackEvent.TraceId, e.StackEvent.Pid, e.StackEvent.Location, e.StackEvent.Goid, e.StackEvent.TimeNsStart, e.StackEvent.Ip, e.StackEvent.CallerIp, e.StackEvent.Bp, e.StackEvent.CallerBp)
  429. }
  430. c.StackProcess2(*e.StackEvent, r.tracer)
  431. } else {
  432. // fmt.Printf("e.EventTypeFunEnt ErrorError: TraceId:%d, Pid:%d, Location:%d, Goid:%d, TimeNs:%d, Ip:%X, CallerIp:%x, Bp:%x, CallerBp:%x", e.StackEvent.TraceId, e.StackEvent.Pid, e.StackEvent.Location, e.StackEvent.Goid, e.StackEvent.TimeNsStart, e.StackEvent.Ip, e.StackEvent.CallerIp, e.StackEvent.Bp, e.StackEvent.CallerBp)
  433. // fmt.Printf("e.EventTypeFunEnt ErrorError: TraceId:%x, FPid:%x, Nid:%x, Level:%d\n", e.StackEvent.Fpid, e.StackEvent.Nid, e.StackEvent.Level)
  434. }
  435. }
  436. }
  437. }
  438. }
  439. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  440. if c, seen := r.containersByPid[pid]; c != nil {
  441. return c
  442. } else if seen { // ignored
  443. return nil
  444. }
  445. cg, err := proc.ReadCgroup(pid)
  446. if err != nil {
  447. if !common.IsNotExist(err) {
  448. klog.Warningln("failed to read proc cgroup:", err)
  449. }
  450. return nil
  451. }
  452. cgId := fmt.Sprintf("%s/%d", cg.Id, pid)
  453. if c := r.containersByCgroupId[cgId]; c != nil {
  454. r.containersByPid[pid] = c
  455. return c
  456. }
  457. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  458. cmdline := proc.GetCmdline(pid)
  459. parts := bytes.Split(cmdline, []byte{0})
  460. if len(parts) > 0 {
  461. cmd := parts[0]
  462. lastArg := parts[len(parts)-1]
  463. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  464. cg.ContainerId = string(lastArg)
  465. }
  466. }
  467. }
  468. md, err := getContainerMetadata(cg)
  469. if err != nil {
  470. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  471. return nil
  472. }
  473. // add ns/workload/podname
  474. id, extensionTag := calcId(cg, md, pid)
  475. //klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  476. if id == "" {
  477. if cg.Id == "/init.scope" && pid != 1 {
  478. klog.Infoln("ignoring without persisting", "cg", cg.Id, "pid", pid)
  479. } else {
  480. klog.Infoln("ignoring", "cg", cg.Id, "pid", pid)
  481. r.containersByPid[pid] = nil
  482. }
  483. return nil
  484. }
  485. if c := r.containersById[id]; c != nil {
  486. //klog.Warningln("id conflict:", id)
  487. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  488. c.cgroup = cg
  489. c.metadata = md
  490. c.runLogParser("")
  491. if c.nsConntrack != nil {
  492. _ = c.nsConntrack.Close()
  493. c.nsConntrack = nil
  494. }
  495. }
  496. setK8sTag(c, extensionTag, pid)
  497. r.containersByPid[pid] = c
  498. r.containersByCgroupId[cgId] = c
  499. return c
  500. }
  501. c, err := NewContainer(id, cg, md, r.hostConntrack, pid, r)
  502. if err != nil {
  503. klog.Warningf("failed to create container pid=%d cg=%s id=%s: %s", pid, cg.Id, id, err)
  504. return nil
  505. }
  506. //klog.Infoln("detected a new container", "pid", pid, "cg", cg.Id, "id", id)
  507. // add ns/workload/podname/pid/ctype
  508. //sType := fmt.Sprintf("%d", cg.ContainerType)
  509. setK8sTag(c, extensionTag, pid)
  510. if err := prometheus.WrapRegistererWith(setLabels(string(id),
  511. extensionTag[Namespace],
  512. extensionTag[Workload],
  513. extensionTag[PodName],
  514. extensionTag[ProcessName],
  515. fmt.Sprintf("%d", pid)), r.reg).Register(c); err != nil {
  516. klog.Warningln("failed to register container:", err)
  517. return nil
  518. }
  519. r.containersByPid[pid] = c
  520. r.containersByCgroupId[cgId] = c
  521. r.containersById[id] = c
  522. return c
  523. }
  524. func (r *Registry) updateTrafficStatsIfNecessary() {
  525. r.trafficStatsLock.Lock()
  526. defer r.trafficStatsLock.Unlock()
  527. if time.Now().Sub(r.trafficStatsLastUpdated) < MinTrafficStatsUpdateInterval {
  528. return
  529. }
  530. iter := r.tracer.ActiveConnectionsIterator()
  531. cid := ebpftracer.ConnectionId{}
  532. stats := ebpftracer.Connection{}
  533. for iter.Next(&cid, &stats) {
  534. r.trafficStatsUpdateCh <- &TrafficStatsUpdate{
  535. Pid: cid.PID,
  536. FD: cid.FD,
  537. BytesSent: stats.BytesSent,
  538. BytesReceived: stats.BytesReceived,
  539. }
  540. }
  541. if err := iter.Err(); err != nil {
  542. klog.Warningln(err)
  543. }
  544. r.trafficStatsUpdateCh <- nil
  545. r.trafficStatsLastUpdated = time.Now()
  546. }
  547. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata, pid uint32) (ContainerID, map[string]string) {
  548. // 卡一下防止概率性获取为bash
  549. time.Sleep(1 * time.Millisecond)
  550. procName := proc.GetProcName(pid)
  551. extensionTag := map[string]string{Namespace: "", Workload: "", PodName: "", ProcessName: procName}
  552. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  553. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  554. return "", extensionTag
  555. }
  556. return ContainerID(cg.ContainerId), extensionTag
  557. }
  558. if cg.ContainerType == cgroup.ContainerTypeStandaloneProcess {
  559. //extensionTag[ProcessName] = procName
  560. return ContainerID(fmt.Sprintf("/%s/%s/%d", "standalone", procName, pid)), extensionTag
  561. }
  562. switch cg.ContainerType {
  563. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  564. default:
  565. return "", extensionTag
  566. }
  567. if cg.ContainerId == "" {
  568. return "", extensionTag
  569. }
  570. if md.labels["io.kubernetes.pod.name"] != "" {
  571. pod := md.labels["io.kubernetes.pod.name"]
  572. namespace := md.labels["io.kubernetes.pod.namespace"]
  573. name := md.labels["io.kubernetes.container.name"]
  574. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  575. name = "sandbox"
  576. }
  577. if name == "" || name == "POD" { // skip pause containers
  578. return "", extensionTag
  579. }
  580. extensionTag[Namespace] = namespace
  581. if *flags.RunInContainer {
  582. extensionTag[Workload], _ = kube.GetWorkload(namespace, pod)
  583. }
  584. extensionTag[PodName] = pod
  585. //extensionTag[ProcessName] = name
  586. if g := cronjobPodName.FindStringSubmatch(pod); len(g) == 3 {
  587. now := time.Now()
  588. tsMiniutes, _ := strconv.ParseUint(g[2], 10, 64)
  589. scheduledAt := time.Unix(int64(tsMiniutes)*60, 0)
  590. if scheduledAt.After(now.Add(-cronjobPodScheduleWindow)) && scheduledAt.Before(now.Add(cronjobPodScheduleWindow)) {
  591. return ContainerID(fmt.Sprintf("/k8s-cronjob/%s/%s/%s", namespace, g[1], name)), extensionTag
  592. }
  593. }
  594. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name)), extensionTag
  595. }
  596. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  597. namespace := md.labels["com.docker.stack.namespace"]
  598. service := md.labels["com.docker.swarm.service.name"]
  599. if namespace != "" {
  600. service = strings.TrimPrefix(service, namespace+"_")
  601. }
  602. if namespace == "" {
  603. namespace = "_"
  604. }
  605. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1])), extensionTag
  606. }
  607. if md.env != nil {
  608. allocId := md.env["NOMAD_ALLOC_ID"]
  609. group := md.env["NOMAD_GROUP_NAME"]
  610. job := md.env["NOMAD_JOB_NAME"]
  611. namespace := md.env["NOMAD_NAMESPACE"]
  612. task := md.env["NOMAD_TASK_NAME"]
  613. if allocId != "" && group != "" && job != "" && namespace != "" && task != "" {
  614. return ContainerID(fmt.Sprintf("/nomad/%s/%s/%s/%s/%s", namespace, job, group, allocId, task)), extensionTag
  615. }
  616. }
  617. if md.name == "" { // should be "pure" dockerd container here
  618. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  619. return "", extensionTag
  620. }
  621. return ContainerID("/docker/" + md.name), extensionTag
  622. }
  623. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  624. switch cg.ContainerType {
  625. case cgroup.ContainerTypeSystemdService:
  626. md := &ContainerMetadata{}
  627. md.systemdTriggeredBy = SystemdTriggeredBy(cg.ContainerId)
  628. return md, nil
  629. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  630. default:
  631. return &ContainerMetadata{}, nil
  632. }
  633. if cg.ContainerId == "" {
  634. return &ContainerMetadata{}, nil
  635. }
  636. if cg.ContainerType == cgroup.ContainerTypeCrio {
  637. return CrioInspect(cg.ContainerId)
  638. }
  639. var dockerdErr error
  640. if dockerdClient != nil {
  641. md, err := DockerdInspect(cg.ContainerId)
  642. if err == nil {
  643. return md, nil
  644. }
  645. dockerdErr = err
  646. }
  647. var containerdErr error
  648. if containerdClient != nil {
  649. md, err := ContainerdInspect(cg.ContainerId)
  650. if err == nil {
  651. return md, nil
  652. }
  653. containerdErr = err
  654. }
  655. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  656. }
  657. type TrafficStatsUpdate struct {
  658. Pid uint32
  659. FD uint64
  660. BytesSent uint64
  661. BytesReceived uint64
  662. }