registry.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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(setLabels(string(id),
  158. c.K8sContainer.ns,
  159. c.K8sContainer.podName,
  160. c.K8sContainer.containerName,
  161. c.K8sContainer.pid), r.reg).Unregister(c); !ok {
  162. klog.Warningln("failed to unregister container:", id)
  163. }
  164. delete(r.containersById, id)
  165. c.Close()
  166. }
  167. r.ip2fqdnLock.Lock()
  168. for ip := range r.ip2fqdn {
  169. if _, ok := activeIPs[ip]; !ok {
  170. delete(r.ip2fqdn, ip)
  171. }
  172. }
  173. r.ip2fqdnLock.Unlock()
  174. case e, more := <-ch:
  175. if e.Pid == uint32(os.Getpid()) {
  176. continue
  177. }
  178. if !more {
  179. return
  180. }
  181. switch e.Type {
  182. case ebpftracer.EventTypeProcessStart:
  183. c, seen := r.containersByPid[e.Pid]
  184. switch { // possible pids wraparound + missed `process-exit` event
  185. case c == nil && seen: // ignored
  186. delete(r.containersByPid, e.Pid)
  187. case c != nil: // revalidating by cgroup
  188. cg, err := proc.ReadCgroup(e.Pid)
  189. if err != nil || cg.Id != c.cgroup.Id {
  190. delete(r.containersByPid, e.Pid)
  191. c.onProcessExit(e.Pid, false)
  192. }
  193. }
  194. if c := r.getOrCreateContainer(e.Pid); c != nil {
  195. p := c.onProcessStart(e.Pid)
  196. if r.processInfoCh != nil && p != nil {
  197. r.processInfoCh <- ProcessInfo{Pid: p.Pid, ContainerId: c.id, StartedAt: p.StartedAt}
  198. }
  199. }
  200. case ebpftracer.EventTypeProcessExit:
  201. if c := r.containersByPid[e.Pid]; c != nil {
  202. c.onProcessExit(e.Pid, e.Reason == ebpftracer.EventReasonOOMKill)
  203. }
  204. delete(r.containersByPid, e.Pid)
  205. case ebpftracer.EventTypeFileOpen:
  206. if c := r.getOrCreateContainer(e.Pid); c != nil {
  207. c.onFileOpen(e.Pid, e.Fd)
  208. }
  209. case ebpftracer.EventTypeListenOpen:
  210. //fmt.Println("ebpftracer.EventTypeConnectionOpen==================", e.Pid)
  211. if c := r.getOrCreateContainer(e.Pid); c != nil {
  212. c.onListenOpen(e.Pid, e.SrcAddr, false)
  213. c.buildInstanceID()
  214. c.attachTlsUprobes(r.tracer, e.Pid)
  215. } else {
  216. klog.Infoln("TCP listen open from unknown container", e)
  217. }
  218. case ebpftracer.EventTypeListenClose:
  219. if c := r.containersByPid[e.Pid]; c != nil {
  220. c.onListenClose(e.Pid, e.SrcAddr)
  221. }
  222. case ebpftracer.EventTypeConnectionOpen:
  223. //fmt.Println("ebpftracer.EventTypeConnectionOpen==================", e.Pid)
  224. if c := r.getOrCreateContainer(e.Pid); c != nil {
  225. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false)
  226. c.attachTlsUprobes(r.tracer, e.Pid)
  227. } else {
  228. klog.Infoln("TCP connection from unknown container", e)
  229. }
  230. case ebpftracer.EventTypeConnectionError:
  231. if c := r.getOrCreateContainer(e.Pid); c != nil {
  232. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, 0, true)
  233. } else {
  234. klog.Infoln("TCP connection error from unknown container", e)
  235. }
  236. case ebpftracer.EventTypeConnectionClose:
  237. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  238. for _, c := range r.containersById {
  239. if c.onConnectionClose(srcDst) {
  240. break
  241. }
  242. }
  243. case ebpftracer.EventTypeTCPRetransmit:
  244. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  245. for _, c := range r.containersById {
  246. if c.onRetransmit(srcDst) {
  247. break
  248. }
  249. }
  250. case ebpftracer.EventTypeL7Request:
  251. //fmt.Println("EventTypeL7Request")
  252. //fmt.Println("e.L7Request Payload:", string(e.L7Request.Payload))
  253. if e.L7Request == nil {
  254. continue
  255. }
  256. if c := r.containersByPid[e.Pid]; c != nil {
  257. ip2fqdn := c.onL7RequestApm(e.Pid, e.Fd, e.Timestamp, e.L7Request)
  258. r.ip2fqdnLock.Lock()
  259. for ip, fqdn := range ip2fqdn {
  260. r.ip2fqdn[ip] = fqdn
  261. }
  262. r.ip2fqdnLock.Unlock()
  263. }
  264. }
  265. }
  266. }
  267. }
  268. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  269. if c, seen := r.containersByPid[pid]; c != nil {
  270. return c
  271. } else if seen { // ignored
  272. return nil
  273. }
  274. cg, err := proc.ReadCgroup(pid)
  275. if err != nil {
  276. if !common.IsNotExist(err) {
  277. klog.Warningln("failed to read proc cgroup:", err)
  278. }
  279. return nil
  280. }
  281. cgId := fmt.Sprintf("%s/%d", cg.Id, pid)
  282. if c := r.containersByCgroupId[cgId]; c != nil {
  283. r.containersByPid[pid] = c
  284. return c
  285. }
  286. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  287. cmdline := proc.GetCmdline(pid)
  288. parts := bytes.Split(cmdline, []byte{0})
  289. if len(parts) > 0 {
  290. cmd := parts[0]
  291. lastArg := parts[len(parts)-1]
  292. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  293. cg.ContainerId = string(lastArg)
  294. }
  295. }
  296. }
  297. md, err := getContainerMetadata(cg)
  298. if err != nil {
  299. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  300. return nil
  301. }
  302. // add ns/workload/podname
  303. id, extensionTag := calcId(cg, md, pid)
  304. //klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  305. if id == "" {
  306. if cg.Id == "/init.scope" && pid != 1 {
  307. klog.InfoS("ignoring without persisting", "cg", cg.Id, "pid", pid)
  308. } else {
  309. klog.InfoS("ignoring", "cg", cg.Id, "pid", pid)
  310. r.containersByPid[pid] = nil
  311. }
  312. return nil
  313. }
  314. if c := r.containersById[id]; c != nil {
  315. klog.Warningln("id conflict:", id)
  316. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  317. c.cgroup = cg
  318. c.metadata = md
  319. c.runLogParser("")
  320. if c.nsConntrack != nil {
  321. _ = c.nsConntrack.Close()
  322. c.nsConntrack = nil
  323. }
  324. }
  325. setK8sTag(c, extensionTag, pid)
  326. r.containersByPid[pid] = c
  327. r.containersByCgroupId[cgId] = c
  328. return c
  329. }
  330. c, err := NewContainer(id, cg, md, r.hostConntrack, pid)
  331. if err != nil {
  332. klog.Warningf("failed to create container pid=%d cg=%s id=%s: %s", pid, cg.Id, id, err)
  333. return nil
  334. }
  335. //klog.InfoS("detected a new container", "pid", pid, "cg", cg.Id, "id", id)
  336. // add ns/workload/podname/pid/ctype
  337. //sType := fmt.Sprintf("%d", cg.ContainerType)
  338. setK8sTag(c, extensionTag, pid)
  339. if err := prometheus.WrapRegistererWith(setLabels(string(id),
  340. extensionTag[Namespace],
  341. extensionTag[PodName],
  342. extensionTag[ProcessName],
  343. fmt.Sprintf("%d", pid)), r.reg).Register(c); err != nil {
  344. klog.Warningln("failed to register container:", err)
  345. return nil
  346. }
  347. r.containersByPid[pid] = c
  348. r.containersByCgroupId[cgId] = c
  349. r.containersById[id] = c
  350. return c
  351. }
  352. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata, pid uint32) (ContainerID, map[string]string) {
  353. extensionTag := map[string]string{Namespace: "", Workload: "", PodName: "", ProcessName: ""}
  354. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  355. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  356. return "", extensionTag
  357. }
  358. return ContainerID(cg.ContainerId), extensionTag
  359. }
  360. if cg.ContainerType == cgroup.ContainerTypeStandaloneProcess {
  361. procName := proc.GetProcName(pid)
  362. extensionTag[ProcessName] = procName
  363. return ContainerID(fmt.Sprintf("/%s/%s/%d", "standalone", proc.GetProcName(pid), pid)), extensionTag
  364. }
  365. switch cg.ContainerType {
  366. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  367. default:
  368. return "", extensionTag
  369. }
  370. if cg.ContainerId == "" {
  371. return "", extensionTag
  372. }
  373. if md.labels["io.kubernetes.pod.name"] != "" {
  374. pod := md.labels["io.kubernetes.pod.name"]
  375. namespace := md.labels["io.kubernetes.pod.namespace"]
  376. name := md.labels["io.kubernetes.container.name"]
  377. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  378. name = "sandbox"
  379. }
  380. if name == "" || name == "POD" { // skip pause containers
  381. return "", extensionTag
  382. }
  383. extensionTag[Namespace] = namespace
  384. extensionTag[Workload] = ""
  385. extensionTag[PodName] = pod
  386. extensionTag[ProcessName] = name
  387. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name)), extensionTag
  388. }
  389. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  390. namespace := md.labels["com.docker.stack.namespace"]
  391. service := md.labels["com.docker.swarm.service.name"]
  392. if namespace != "" {
  393. service = strings.TrimPrefix(service, namespace+"_")
  394. }
  395. if namespace == "" {
  396. namespace = "_"
  397. }
  398. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1])), extensionTag
  399. }
  400. if md.name == "" { // should be "pure" dockerd container here
  401. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  402. return "", extensionTag
  403. }
  404. return ContainerID("/docker/" + md.name), extensionTag
  405. }
  406. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  407. switch cg.ContainerType {
  408. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  409. default:
  410. return &ContainerMetadata{}, nil
  411. }
  412. if cg.ContainerId == "" {
  413. return &ContainerMetadata{}, nil
  414. }
  415. if cg.ContainerType == cgroup.ContainerTypeCrio {
  416. return CrioInspect(cg.ContainerId)
  417. }
  418. var dockerdErr error
  419. if dockerdClient != nil {
  420. md, err := DockerdInspect(cg.ContainerId)
  421. if err == nil {
  422. return md, nil
  423. }
  424. dockerdErr = err
  425. }
  426. var containerdErr error
  427. if containerdClient != nil {
  428. md, err := ContainerdInspect(cg.ContainerId)
  429. if err == nil {
  430. return md, nil
  431. }
  432. containerdErr = err
  433. }
  434. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  435. }