registry.go 19 KB

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