registry.go 14 KB

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