registry.go 19 KB

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