registry.go 21 KB

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