registry.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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(os.Getenv("CONFIG_ENDPOINT"), 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("New Proxy Client error,Please check export CONFIG_ENDPOINT=")
  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]modelse.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. } else {
  181. klog.WithField("pid", pid).Infoln("[registry] Attach Stack success!")
  182. }
  183. }
  184. }
  185. if !verifyAttachConditions && c.checkL7AttachReady() {
  186. // detach
  187. c.detachUprobes(pid)
  188. }
  189. }
  190. if c.AppInfo.AppName != "" {
  191. detail := modelse.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. c.RegisterAppInfo(r, e.Pid)
  304. c.attachUprobes(r.tracer, e.Pid)
  305. err := c.stackTrace(r.tracer, e.Pid)
  306. if err != nil {
  307. klog.Errorf("Stack trace error", err)
  308. }
  309. }
  310. } else {
  311. klog.Infoln("TCP listen open from unknown container", e)
  312. }
  313. case ebpftracer.EventTypeConnectionOpen:
  314. //fmt.Println("ebpftracer.EventTypeConnectionOpen==================", e.Pid)
  315. if c := r.getOrCreateContainer(e.Pid); c != nil {
  316. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false)
  317. c.eventReady()
  318. if common.IsOpenFilter() && common.IsFilterPid(e.Pid) {
  319. c.WhiteSettingInfo.AppName = enums.TestApp
  320. c.RegisterAppInfo(r, e.Pid)
  321. c.attachUprobes(r.tracer, e.Pid)
  322. err := c.stackTrace(r.tracer, e.Pid)
  323. if err != nil {
  324. klog.Errorf("Stack trace error", err)
  325. }
  326. }
  327. } else {
  328. klog.Infoln("TCP connection from unknown container", e)
  329. }
  330. case ebpftracer.EventTypeListenClose:
  331. if c := r.containersByPid[e.Pid]; c != nil {
  332. c.onListenClose(e.Pid, e.SrcAddr)
  333. }
  334. case ebpftracer.EventTypeConnectionError:
  335. if c := r.getOrCreateContainer(e.Pid); c != nil {
  336. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, 0, true)
  337. } else {
  338. klog.Infoln("TCP connection error from unknown container", e)
  339. }
  340. case ebpftracer.EventTypeConnectionClose:
  341. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  342. for _, c := range r.containersById {
  343. if c.onConnectionClose(srcDst) {
  344. break
  345. }
  346. }
  347. case ebpftracer.EventTypeTCPRetransmit:
  348. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  349. for _, c := range r.containersById {
  350. if c.onRetransmit(srcDst) {
  351. break
  352. }
  353. }
  354. case ebpftracer.EventTypeL7Request:
  355. //fmt.Println("e.L7Request Payload:", string(e.L7Request.Payload))
  356. if e.L7Request == nil {
  357. continue
  358. }
  359. if c := r.containersByPid[e.Pid]; c != nil {
  360. //fmt.Println("EventTypeL7Request", e.Pid, c.checkL7AttachReady())
  361. //a, _ := json.Marshal(e.L7Request)
  362. //fmt.Println("EventTypeL7Request", e.Pid, string(a))
  363. ip2fqdn := c.onL7RequestApm(e.Pid, e.Fd, e.Timestamp, e.L7Request)
  364. r.ip2fqdnLock.Lock()
  365. for ip, fqdn := range ip2fqdn {
  366. r.ip2fqdn[ip] = fqdn
  367. }
  368. r.ip2fqdnLock.Unlock()
  369. }
  370. case ebpftracer.EventTypeFunEnt:
  371. if e.StackEvent == nil {
  372. continue
  373. }
  374. if c := r.containersByPid[uint32(e.StackEvent.Pid)]; c != nil {
  375. 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)
  376. c.StackProcess2(*e.StackEvent, r.tracer)
  377. } else {
  378. // 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)
  379. // fmt.Printf("e.EventTypeFunEnt ErrorError: TraceId:%x, FPid:%x, Nid:%x, Level:%d\n", e.StackEvent.Fpid, e.StackEvent.Nid, e.StackEvent.Level)
  380. }
  381. }
  382. }
  383. }
  384. }
  385. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  386. if c, seen := r.containersByPid[pid]; c != nil {
  387. return c
  388. } else if seen { // ignored
  389. return nil
  390. }
  391. cg, err := proc.ReadCgroup(pid)
  392. if err != nil {
  393. if !common.IsNotExist(err) {
  394. klog.Warningln("failed to read proc cgroup:", err)
  395. }
  396. return nil
  397. }
  398. cgId := fmt.Sprintf("%s/%d", cg.Id, pid)
  399. if c := r.containersByCgroupId[cgId]; c != nil {
  400. r.containersByPid[pid] = c
  401. return c
  402. }
  403. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  404. cmdline := proc.GetCmdline(pid)
  405. parts := bytes.Split(cmdline, []byte{0})
  406. if len(parts) > 0 {
  407. cmd := parts[0]
  408. lastArg := parts[len(parts)-1]
  409. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  410. cg.ContainerId = string(lastArg)
  411. }
  412. }
  413. }
  414. md, err := getContainerMetadata(cg)
  415. if err != nil {
  416. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  417. return nil
  418. }
  419. // add ns/workload/podname
  420. id, extensionTag := calcId(cg, md, pid)
  421. //klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  422. if id == "" {
  423. if cg.Id == "/init.scope" && pid != 1 {
  424. klog.Infoln("ignoring without persisting", "cg", cg.Id, "pid", pid)
  425. } else {
  426. klog.Infoln("ignoring", "cg", cg.Id, "pid", pid)
  427. r.containersByPid[pid] = nil
  428. }
  429. return nil
  430. }
  431. if c := r.containersById[id]; c != nil {
  432. //klog.Warningln("id conflict:", id)
  433. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  434. c.cgroup = cg
  435. c.metadata = md
  436. c.runLogParser("")
  437. if c.nsConntrack != nil {
  438. _ = c.nsConntrack.Close()
  439. c.nsConntrack = nil
  440. }
  441. }
  442. setK8sTag(c, extensionTag, pid)
  443. r.containersByPid[pid] = c
  444. r.containersByCgroupId[cgId] = c
  445. return c
  446. }
  447. c, err := NewContainer(id, cg, md, r.hostConntrack, pid)
  448. if err != nil {
  449. klog.Warningf("failed to create container pid=%d cg=%s id=%s: %s", pid, cg.Id, id, err)
  450. return nil
  451. }
  452. //klog.Infoln("detected a new container", "pid", pid, "cg", cg.Id, "id", id)
  453. // add ns/workload/podname/pid/ctype
  454. //sType := fmt.Sprintf("%d", cg.ContainerType)
  455. setK8sTag(c, extensionTag, pid)
  456. if err := prometheus.WrapRegistererWith(setLabels(string(id),
  457. extensionTag[Namespace],
  458. extensionTag[PodName],
  459. extensionTag[ProcessName],
  460. fmt.Sprintf("%d", pid)), r.reg).Register(c); err != nil {
  461. klog.Warningln("failed to register container:", err)
  462. return nil
  463. }
  464. r.containersByPid[pid] = c
  465. r.containersByCgroupId[cgId] = c
  466. r.containersById[id] = c
  467. return c
  468. }
  469. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata, pid uint32) (ContainerID, map[string]string) {
  470. extensionTag := map[string]string{Namespace: "", Workload: "", PodName: "", ProcessName: ""}
  471. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  472. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  473. return "", extensionTag
  474. }
  475. return ContainerID(cg.ContainerId), extensionTag
  476. }
  477. if cg.ContainerType == cgroup.ContainerTypeStandaloneProcess {
  478. procName := proc.GetProcName(pid)
  479. extensionTag[ProcessName] = procName
  480. return ContainerID(fmt.Sprintf("/%s/%s/%d", "standalone", proc.GetProcName(pid), pid)), extensionTag
  481. }
  482. switch cg.ContainerType {
  483. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  484. default:
  485. return "", extensionTag
  486. }
  487. if cg.ContainerId == "" {
  488. return "", extensionTag
  489. }
  490. if md.labels["io.kubernetes.pod.name"] != "" {
  491. pod := md.labels["io.kubernetes.pod.name"]
  492. namespace := md.labels["io.kubernetes.pod.namespace"]
  493. name := md.labels["io.kubernetes.container.name"]
  494. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  495. name = "sandbox"
  496. }
  497. if name == "" || name == "POD" { // skip pause containers
  498. return "", extensionTag
  499. }
  500. extensionTag[Namespace] = namespace
  501. extensionTag[Workload] = ""
  502. extensionTag[PodName] = pod
  503. extensionTag[ProcessName] = name
  504. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name)), extensionTag
  505. }
  506. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  507. namespace := md.labels["com.docker.stack.namespace"]
  508. service := md.labels["com.docker.swarm.service.name"]
  509. if namespace != "" {
  510. service = strings.TrimPrefix(service, namespace+"_")
  511. }
  512. if namespace == "" {
  513. namespace = "_"
  514. }
  515. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1])), extensionTag
  516. }
  517. if md.name == "" { // should be "pure" dockerd container here
  518. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  519. return "", extensionTag
  520. }
  521. return ContainerID("/docker/" + md.name), extensionTag
  522. }
  523. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  524. switch cg.ContainerType {
  525. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  526. default:
  527. return &ContainerMetadata{}, nil
  528. }
  529. if cg.ContainerId == "" {
  530. return &ContainerMetadata{}, nil
  531. }
  532. if cg.ContainerType == cgroup.ContainerTypeCrio {
  533. return CrioInspect(cg.ContainerId)
  534. }
  535. var dockerdErr error
  536. if dockerdClient != nil {
  537. md, err := DockerdInspect(cg.ContainerId)
  538. if err == nil {
  539. return md, nil
  540. }
  541. dockerdErr = err
  542. }
  543. var containerdErr error
  544. if containerdClient != nil {
  545. md, err := ContainerdInspect(cg.ContainerId)
  546. if err == nil {
  547. return md, nil
  548. }
  549. containerdErr = err
  550. }
  551. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  552. }