registry.go 19 KB

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