registry.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. package containers
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "regexp"
  7. "strings"
  8. "time"
  9. "github.com/coroot/coroot-node-agent/cgroup"
  10. "github.com/coroot/coroot-node-agent/common"
  11. "github.com/coroot/coroot-node-agent/ebpftracer"
  12. "github.com/coroot/coroot-node-agent/flags"
  13. "github.com/coroot/coroot-node-agent/proc"
  14. "github.com/prometheus/client_golang/prometheus"
  15. "github.com/vishvananda/netns"
  16. "k8s.io/klog/v2"
  17. )
  18. var (
  19. selfNetNs = netns.None()
  20. hostNetNsId = netns.None().UniqueId()
  21. agentPid = uint32(os.Getpid())
  22. containerIdRegexp = regexp.MustCompile(`[a-z0-9]{64}`)
  23. )
  24. type ProcessInfo struct {
  25. Pid uint32
  26. ContainerId ContainerID
  27. StartedAt time.Time
  28. }
  29. type Registry struct {
  30. reg prometheus.Registerer
  31. tracer *ebpftracer.Tracer
  32. events chan ebpftracer.Event
  33. hostConntrack *Conntrack
  34. containersById map[ContainerID]*Container
  35. containersByCgroupId map[string]*Container
  36. containersByPid map[uint32]*Container
  37. processInfoCh chan<- ProcessInfo
  38. }
  39. func NewRegistry(reg prometheus.Registerer, kernelVersion string, processInfoCh chan<- ProcessInfo) (*Registry, error) {
  40. ns, err := proc.GetSelfNetNs()
  41. if err != nil {
  42. return nil, err
  43. }
  44. selfNetNs = ns
  45. hostNetNs, err := proc.GetHostNetNs()
  46. if err != nil {
  47. return nil, err
  48. }
  49. defer hostNetNs.Close()
  50. hostNetNsId = hostNetNs.UniqueId()
  51. err = proc.ExecuteInNetNs(hostNetNs, selfNetNs, func() error {
  52. if err := TaskstatsInit(); err != nil {
  53. return err
  54. }
  55. return nil
  56. })
  57. if err != nil {
  58. return nil, err
  59. }
  60. if err := cgroup.Init(); err != nil {
  61. return nil, err
  62. }
  63. if err := DockerdInit(); err != nil {
  64. klog.Warningln(err)
  65. }
  66. if err := ContainerdInit(); err != nil {
  67. klog.Warningln(err)
  68. }
  69. if err := CrioInit(); err != nil {
  70. klog.Warningln(err)
  71. }
  72. if err := JournaldInit(); err != nil {
  73. klog.Warningln(err)
  74. }
  75. ct, err := NewConntrack(hostNetNs)
  76. if err != nil {
  77. return nil, err
  78. }
  79. r := &Registry{
  80. reg: reg,
  81. events: make(chan ebpftracer.Event, 10000),
  82. hostConntrack: ct,
  83. containersById: map[ContainerID]*Container{},
  84. containersByCgroupId: map[string]*Container{},
  85. containersByPid: map[uint32]*Container{},
  86. processInfoCh: processInfoCh,
  87. tracer: ebpftracer.NewTracer(kernelVersion, *flags.DisableL7Tracing),
  88. }
  89. go r.handleEvents(r.events)
  90. if err = r.tracer.Run(r.events); err != nil {
  91. close(r.events)
  92. return nil, err
  93. }
  94. return r, nil
  95. }
  96. func (r *Registry) Close() {
  97. r.tracer.Close()
  98. close(r.events)
  99. }
  100. func (r *Registry) handleEvents(ch <-chan ebpftracer.Event) {
  101. gcTicker := time.NewTicker(gcInterval)
  102. defer gcTicker.Stop()
  103. for {
  104. select {
  105. case now := <-gcTicker.C:
  106. for pid, c := range r.containersByPid {
  107. cg, err := proc.ReadCgroup(pid)
  108. if err != nil {
  109. delete(r.containersByPid, pid)
  110. if c != nil {
  111. c.onProcessExit(pid, false)
  112. }
  113. continue
  114. }
  115. if c != nil && cg.Id != c.cgroup.Id {
  116. delete(r.containersByPid, pid)
  117. c.onProcessExit(pid, false)
  118. }
  119. }
  120. for id, c := range r.containersById {
  121. if !c.Dead(now) {
  122. continue
  123. }
  124. klog.Infoln("deleting dead container:", id)
  125. for cg, cc := range r.containersByCgroupId {
  126. if cc == c {
  127. delete(r.containersByCgroupId, cg)
  128. }
  129. }
  130. for pid, cc := range r.containersByPid {
  131. if cc == c {
  132. delete(r.containersByPid, pid)
  133. }
  134. }
  135. if ok := prometheus.WrapRegistererWith(setLabels(string(id),
  136. c.K8sContainer.ns,
  137. c.K8sContainer.podName,
  138. c.K8sContainer.containerName,
  139. c.K8sContainer.pid), r.reg).Unregister(c); !ok {
  140. klog.Warningln("failed to unregister container:", id)
  141. }
  142. delete(r.containersById, id)
  143. c.Close()
  144. }
  145. case e, more := <-ch:
  146. if e.Pid == uint32(os.Getpid()) {
  147. continue
  148. }
  149. if !more {
  150. return
  151. }
  152. switch e.Type {
  153. case ebpftracer.EventTypeProcessStart:
  154. c, seen := r.containersByPid[e.Pid]
  155. switch { // possible pids wraparound + missed `process-exit` event
  156. case c == nil && seen: // ignored
  157. delete(r.containersByPid, e.Pid)
  158. case c != nil: // revalidating by cgroup
  159. cg, err := proc.ReadCgroup(e.Pid)
  160. if err != nil || cg.Id != c.cgroup.Id {
  161. delete(r.containersByPid, e.Pid)
  162. c.onProcessExit(e.Pid, false)
  163. }
  164. }
  165. if c := r.getOrCreateContainer(e.Pid); c != nil {
  166. p := c.onProcessStart(e.Pid)
  167. if r.processInfoCh != nil && p != nil {
  168. r.processInfoCh <- ProcessInfo{Pid: p.Pid, ContainerId: c.id, StartedAt: p.StartedAt}
  169. }
  170. }
  171. case ebpftracer.EventTypeProcessExit:
  172. if c := r.containersByPid[e.Pid]; c != nil {
  173. c.onProcessExit(e.Pid, e.Reason == ebpftracer.EventReasonOOMKill)
  174. }
  175. delete(r.containersByPid, e.Pid)
  176. case ebpftracer.EventTypeFileOpen:
  177. if c := r.getOrCreateContainer(e.Pid); c != nil {
  178. c.onFileOpen(e.Pid, e.Fd)
  179. }
  180. case ebpftracer.EventTypeListenOpen:
  181. if c := r.getOrCreateContainer(e.Pid); c != nil {
  182. c.onListenOpen(e.Pid, e.SrcAddr, false)
  183. } else {
  184. klog.Infoln("TCP listen open from unknown container", e)
  185. }
  186. case ebpftracer.EventTypeListenClose:
  187. if c := r.containersByPid[e.Pid]; c != nil {
  188. c.onListenClose(e.Pid, e.SrcAddr)
  189. }
  190. case ebpftracer.EventTypeConnectionOpen:
  191. if c := r.getOrCreateContainer(e.Pid); c != nil {
  192. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false)
  193. c.attachTlsUprobes(r.tracer, e.Pid)
  194. } else {
  195. klog.Infoln("TCP connection from unknown container", e)
  196. }
  197. case ebpftracer.EventTypeConnectionError:
  198. if c := r.getOrCreateContainer(e.Pid); c != nil {
  199. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, 0, true)
  200. } else {
  201. klog.Infoln("TCP connection error from unknown container", e)
  202. }
  203. case ebpftracer.EventTypeConnectionClose:
  204. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  205. for _, c := range r.containersById {
  206. if c.onConnectionClose(srcDst) {
  207. break
  208. }
  209. }
  210. case ebpftracer.EventTypeTCPRetransmit:
  211. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  212. for _, c := range r.containersById {
  213. if c.onRetransmit(srcDst) {
  214. break
  215. }
  216. }
  217. case ebpftracer.EventTypeL7Request:
  218. fmt.Println("EventTypeL7Request")
  219. fmt.Println("e.L7Request Payload:", string(e.L7Request.Payload))
  220. if e.L7Request == nil {
  221. continue
  222. }
  223. if c := r.containersByPid[e.Pid]; c != nil {
  224. c.onL7RequestApm(e.Pid, e.Fd, e.Timestamp, e.L7Request)
  225. }
  226. }
  227. }
  228. }
  229. }
  230. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  231. if c, seen := r.containersByPid[pid]; c != nil {
  232. return c
  233. } else if seen { // ignored
  234. return nil
  235. }
  236. cg, err := proc.ReadCgroup(pid)
  237. if err != nil {
  238. if !common.IsNotExist(err) {
  239. klog.Warningln("failed to read proc cgroup:", err)
  240. }
  241. return nil
  242. }
  243. cgId := fmt.Sprintf("%s/%d", cg.Id, pid)
  244. if c := r.containersByCgroupId[cgId]; c != nil {
  245. r.containersByPid[pid] = c
  246. return c
  247. }
  248. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  249. cmdline := proc.GetCmdline(pid)
  250. parts := bytes.Split(cmdline, []byte{0})
  251. if len(parts) > 0 {
  252. cmd := parts[0]
  253. lastArg := parts[len(parts)-1]
  254. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  255. cg.ContainerId = string(lastArg)
  256. }
  257. }
  258. }
  259. md, err := getContainerMetadata(cg)
  260. if err != nil {
  261. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  262. return nil
  263. }
  264. // add ns/workload/podname
  265. id, extensionTag := calcId(cg, md, pid)
  266. klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  267. if id == "" {
  268. if cg.Id == "/init.scope" && pid != 1 {
  269. klog.InfoS("ignoring without persisting", "cg", cg.Id, "pid", pid)
  270. } else {
  271. klog.InfoS("ignoring", "cg", cg.Id, "pid", pid)
  272. r.containersByPid[pid] = nil
  273. }
  274. return nil
  275. }
  276. if c := r.containersById[id]; c != nil {
  277. klog.Warningln("id conflict:", id)
  278. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  279. c.cgroup = cg
  280. c.metadata = md
  281. c.runLogParser("")
  282. if c.nsConntrack != nil {
  283. _ = c.nsConntrack.Close()
  284. c.nsConntrack = nil
  285. }
  286. }
  287. setK8sTag(c, extensionTag, pid)
  288. r.containersByPid[pid] = c
  289. r.containersByCgroupId[cgId] = c
  290. return c
  291. }
  292. c, err := NewContainer(id, cg, md, r.hostConntrack, pid)
  293. if err != nil {
  294. klog.Warningf("failed to create container pid=%d cg=%s id=%s: %s", pid, cg.Id, id, err)
  295. return nil
  296. }
  297. klog.InfoS("detected a new container", "pid", pid, "cg", cg.Id, "id", id)
  298. // add ns/workload/podname/pid/ctype
  299. //sType := fmt.Sprintf("%d", cg.ContainerType)
  300. setK8sTag(c, extensionTag, pid)
  301. if err := prometheus.WrapRegistererWith(setLabels(string(id),
  302. extensionTag[Namespace],
  303. extensionTag[PodName],
  304. extensionTag[ProcessName],
  305. fmt.Sprintf("%d", pid)), r.reg).Register(c); err != nil {
  306. klog.Warningln("failed to register container:", err)
  307. return nil
  308. }
  309. r.containersByPid[pid] = c
  310. r.containersByCgroupId[cgId] = c
  311. r.containersById[id] = c
  312. return c
  313. }
  314. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata, pid uint32) (ContainerID, map[string]string) {
  315. extensionTag := map[string]string{Namespace: "", Workload: "", PodName: "", ProcessName: ""}
  316. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  317. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  318. return "", extensionTag
  319. }
  320. return ContainerID(cg.ContainerId), extensionTag
  321. }
  322. if cg.ContainerType == cgroup.ContainerTypeStandaloneProcess {
  323. procName := proc.GetProcName(pid)
  324. extensionTag[ProcessName] = procName
  325. return ContainerID(fmt.Sprintf("/%s/%s/%d", "standalone", proc.GetProcName(pid), pid)), extensionTag
  326. }
  327. switch cg.ContainerType {
  328. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  329. default:
  330. return "", extensionTag
  331. }
  332. if cg.ContainerId == "" {
  333. return "", extensionTag
  334. }
  335. if md.labels["io.kubernetes.pod.name"] != "" {
  336. pod := md.labels["io.kubernetes.pod.name"]
  337. namespace := md.labels["io.kubernetes.pod.namespace"]
  338. name := md.labels["io.kubernetes.container.name"]
  339. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  340. name = "sandbox"
  341. }
  342. if name == "" || name == "POD" { // skip pause containers
  343. return "", extensionTag
  344. }
  345. extensionTag[Namespace] = namespace
  346. extensionTag[Workload] = ""
  347. extensionTag[PodName] = pod
  348. extensionTag[ProcessName] = name
  349. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name)), extensionTag
  350. }
  351. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  352. namespace := md.labels["com.docker.stack.namespace"]
  353. service := md.labels["com.docker.swarm.service.name"]
  354. if namespace != "" {
  355. service = strings.TrimPrefix(service, namespace+"_")
  356. }
  357. if namespace == "" {
  358. namespace = "_"
  359. }
  360. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1])), extensionTag
  361. }
  362. if md.name == "" { // should be "pure" dockerd container here
  363. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  364. return "", extensionTag
  365. }
  366. return ContainerID("/docker/" + md.name), extensionTag
  367. }
  368. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  369. switch cg.ContainerType {
  370. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  371. default:
  372. return &ContainerMetadata{}, nil
  373. }
  374. if cg.ContainerId == "" {
  375. return &ContainerMetadata{}, nil
  376. }
  377. if cg.ContainerType == cgroup.ContainerTypeCrio {
  378. return CrioInspect(cg.ContainerId)
  379. }
  380. var dockerdErr error
  381. if dockerdClient != nil {
  382. md, err := DockerdInspect(cg.ContainerId)
  383. if err == nil {
  384. return md, nil
  385. }
  386. dockerdErr = err
  387. }
  388. var containerdErr error
  389. if containerdClient != nil {
  390. md, err := ContainerdInspect(cg.ContainerId)
  391. if err == nil {
  392. return md, nil
  393. }
  394. containerdErr = err
  395. }
  396. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  397. }