registry.go 13 KB

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