registry.go 11 KB

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