registry.go 21 KB

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