registry.go 19 KB

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