registry.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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(prometheus.Labels{"container_id": string(id)}, r.reg).Unregister(c); !ok {
  136. klog.Warningln("failed to unregister container:", id)
  137. }
  138. delete(r.containersById, id)
  139. c.Close()
  140. }
  141. case e, more := <-ch:
  142. if !more {
  143. return
  144. }
  145. switch e.Type {
  146. case ebpftracer.EventTypeProcessStart:
  147. c, seen := r.containersByPid[e.Pid]
  148. switch { // possible pids wraparound + missed `process-exit` event
  149. case c == nil && seen: // ignored
  150. delete(r.containersByPid, e.Pid)
  151. case c != nil: // revalidating by cgroup
  152. cg, err := proc.ReadCgroup(e.Pid)
  153. if err != nil || cg.Id != c.cgroup.Id {
  154. delete(r.containersByPid, e.Pid)
  155. c.onProcessExit(e.Pid, false)
  156. }
  157. }
  158. if c := r.getOrCreateContainer(e.Pid); c != nil {
  159. p := c.onProcessStart(e.Pid)
  160. if r.processInfoCh != nil && p != nil {
  161. r.processInfoCh <- ProcessInfo{Pid: p.Pid, ContainerId: c.id, StartedAt: p.StartedAt}
  162. }
  163. }
  164. case ebpftracer.EventTypeProcessExit:
  165. if c := r.containersByPid[e.Pid]; c != nil {
  166. c.onProcessExit(e.Pid, e.Reason == ebpftracer.EventReasonOOMKill)
  167. }
  168. delete(r.containersByPid, e.Pid)
  169. case ebpftracer.EventTypeFileOpen:
  170. if c := r.getOrCreateContainer(e.Pid); c != nil {
  171. c.onFileOpen(e.Pid, e.Fd)
  172. }
  173. case ebpftracer.EventTypeListenOpen:
  174. if c := r.getOrCreateContainer(e.Pid); c != nil {
  175. c.onListenOpen(e.Pid, e.SrcAddr, false)
  176. } else {
  177. klog.Infoln("TCP listen open from unknown container", e)
  178. }
  179. case ebpftracer.EventTypeListenClose:
  180. if c := r.containersByPid[e.Pid]; c != nil {
  181. c.onListenClose(e.Pid, e.SrcAddr)
  182. }
  183. case ebpftracer.EventTypeConnectionOpen:
  184. if c := r.getOrCreateContainer(e.Pid); c != nil {
  185. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false)
  186. c.attachTlsUprobes(r.tracer, e.Pid)
  187. } else {
  188. klog.Infoln("TCP connection from unknown container", e)
  189. }
  190. case ebpftracer.EventTypeConnectionError:
  191. if c := r.getOrCreateContainer(e.Pid); c != nil {
  192. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, 0, true)
  193. } else {
  194. klog.Infoln("TCP connection error from unknown container", e)
  195. }
  196. case ebpftracer.EventTypeConnectionClose:
  197. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  198. for _, c := range r.containersById {
  199. if c.onConnectionClose(srcDst) {
  200. break
  201. }
  202. }
  203. case ebpftracer.EventTypeTCPRetransmit:
  204. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  205. for _, c := range r.containersById {
  206. if c.onRetransmit(srcDst) {
  207. break
  208. }
  209. }
  210. case ebpftracer.EventTypeL7Request:
  211. if e.L7Request == nil {
  212. continue
  213. }
  214. if c := r.containersByPid[e.Pid]; c != nil {
  215. c.onL7Request(e.Pid, e.Fd, e.Timestamp, e.L7Request)
  216. }
  217. }
  218. }
  219. }
  220. }
  221. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  222. if c, seen := r.containersByPid[pid]; c != nil {
  223. return c
  224. } else if seen { // ignored
  225. return nil
  226. }
  227. cg, err := proc.ReadCgroup(pid)
  228. if err != nil {
  229. if !common.IsNotExist(err) {
  230. klog.Warningln("failed to read proc cgroup:", err)
  231. }
  232. return nil
  233. }
  234. if c := r.containersByCgroupId[cg.Id]; c != nil {
  235. r.containersByPid[pid] = c
  236. return c
  237. }
  238. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  239. cmdline := proc.GetCmdline(pid)
  240. parts := bytes.Split(cmdline, []byte{0})
  241. if len(parts) > 0 {
  242. cmd := parts[0]
  243. lastArg := parts[len(parts)-1]
  244. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  245. cg.ContainerId = string(lastArg)
  246. }
  247. }
  248. }
  249. md, err := getContainerMetadata(cg)
  250. if err != nil {
  251. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  252. return nil
  253. }
  254. id := calcId(cg, md)
  255. klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  256. if id == "" {
  257. if cg.Id == "/init.scope" && pid != 1 {
  258. klog.InfoS("ignoring without persisting", "cg", cg.Id, "pid", pid)
  259. } else {
  260. klog.InfoS("ignoring", "cg", cg.Id, "pid", pid)
  261. r.containersByPid[pid] = nil
  262. }
  263. return nil
  264. }
  265. if c := r.containersById[id]; c != nil {
  266. klog.Warningln("id conflict:", id)
  267. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  268. c.cgroup = cg
  269. c.metadata = md
  270. c.runLogParser("")
  271. if c.nsConntrack != nil {
  272. _ = c.nsConntrack.Close()
  273. c.nsConntrack = nil
  274. }
  275. }
  276. r.containersByPid[pid] = c
  277. r.containersByCgroupId[cg.Id] = c
  278. return c
  279. }
  280. c, err := NewContainer(id, cg, md, r.hostConntrack, pid)
  281. if err != nil {
  282. klog.Warningf("failed to create container pid=%d cg=%s id=%s: %s", pid, cg.Id, id, err)
  283. return nil
  284. }
  285. klog.InfoS("detected a new container", "pid", pid, "cg", cg.Id, "id", id)
  286. if err := prometheus.WrapRegistererWith(prometheus.Labels{"container_id": string(id)}, r.reg).Register(c); err != nil {
  287. klog.Warningln("failed to register container:", err)
  288. return nil
  289. }
  290. r.containersByPid[pid] = c
  291. r.containersByCgroupId[cg.Id] = c
  292. r.containersById[id] = c
  293. return c
  294. }
  295. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata) ContainerID {
  296. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  297. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  298. return ""
  299. }
  300. return ContainerID(cg.ContainerId)
  301. }
  302. switch cg.ContainerType {
  303. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  304. default:
  305. return ""
  306. }
  307. if cg.ContainerId == "" {
  308. return ""
  309. }
  310. if md.labels["io.kubernetes.pod.name"] != "" {
  311. pod := md.labels["io.kubernetes.pod.name"]
  312. namespace := md.labels["io.kubernetes.pod.namespace"]
  313. name := md.labels["io.kubernetes.container.name"]
  314. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  315. name = "sandbox"
  316. }
  317. if name == "" || name == "POD" { // skip pause containers
  318. return ""
  319. }
  320. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name))
  321. }
  322. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  323. namespace := md.labels["com.docker.stack.namespace"]
  324. service := md.labels["com.docker.swarm.service.name"]
  325. if namespace != "" {
  326. service = strings.TrimPrefix(service, namespace+"_")
  327. }
  328. if namespace == "" {
  329. namespace = "_"
  330. }
  331. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1]))
  332. }
  333. if md.name == "" { // should be "pure" dockerd container here
  334. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  335. return ""
  336. }
  337. return ContainerID("/docker/" + md.name)
  338. }
  339. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  340. switch cg.ContainerType {
  341. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  342. default:
  343. return &ContainerMetadata{}, nil
  344. }
  345. if cg.ContainerId == "" {
  346. return &ContainerMetadata{}, nil
  347. }
  348. if cg.ContainerType == cgroup.ContainerTypeCrio {
  349. return CrioInspect(cg.ContainerId)
  350. }
  351. var dockerdErr error
  352. if dockerdClient != nil {
  353. md, err := DockerdInspect(cg.ContainerId)
  354. if err == nil {
  355. return md, nil
  356. }
  357. dockerdErr = err
  358. }
  359. var containerdErr error
  360. if containerdClient != nil {
  361. md, err := ContainerdInspect(cg.ContainerId)
  362. if err == nil {
  363. return md, nil
  364. }
  365. containerdErr = err
  366. }
  367. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  368. }