registry.go 14 KB

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