registry.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. package containers
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. "github.com/coroot/coroot-node-agent/cgroup"
  12. "github.com/coroot/coroot-node-agent/common"
  13. "github.com/coroot/coroot-node-agent/ebpftracer"
  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. const MinTrafficStatsUpdateInterval = 5 * time.Second
  22. var (
  23. selfNetNs = netns.None()
  24. hostNetNsId = netns.None().UniqueId()
  25. agentPid = uint32(os.Getpid())
  26. containerIdRegexp = regexp.MustCompile(`[a-z0-9]{64}`)
  27. cronjobPodName = regexp.MustCompile(`([a-z0-9-]+)-([0-9]{8})-[bcdfghjklmnpqrstvwxz2456789]{5}`)
  28. cronjobPodScheduleWindow = 7 * 24 * time.Hour
  29. )
  30. type ProcessInfo struct {
  31. Pid uint32
  32. ContainerId ContainerID
  33. StartedAt time.Time
  34. }
  35. type Registry struct {
  36. reg prometheus.Registerer
  37. tracer *ebpftracer.Tracer
  38. events chan ebpftracer.Event
  39. hostConntrack *Conntrack
  40. containersById map[ContainerID]*Container
  41. containersByCgroupId map[string]*Container
  42. containersByPid map[uint32]*Container
  43. ip2fqdn map[netaddr.IP]string
  44. ip2fqdnLock sync.Mutex
  45. processInfoCh chan<- ProcessInfo
  46. trafficStatsLastUpdated time.Time
  47. trafficStatsLock sync.Mutex
  48. trafficStatsUpdateCh chan *TrafficStatsUpdate
  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. trafficStatsUpdateCh: make(chan *TrafficStatsUpdate),
  101. }
  102. if err = reg.Register(r); err != nil {
  103. return nil, err
  104. }
  105. go r.handleEvents(r.events)
  106. if err = r.tracer.Run(r.events); err != nil {
  107. close(r.events)
  108. return nil, err
  109. }
  110. return r, nil
  111. }
  112. func (r *Registry) Describe(ch chan<- *prometheus.Desc) {
  113. ch <- metrics.Ip2Fqdn
  114. }
  115. func (r *Registry) Collect(ch chan<- prometheus.Metric) {
  116. r.ip2fqdnLock.Lock()
  117. defer r.ip2fqdnLock.Unlock()
  118. for ip, fqdn := range r.ip2fqdn {
  119. ch <- gauge(metrics.Ip2Fqdn, 1, ip.String(), fqdn)
  120. }
  121. }
  122. func (r *Registry) Close() {
  123. r.tracer.Close()
  124. close(r.events)
  125. }
  126. func (r *Registry) handleEvents(ch <-chan ebpftracer.Event) {
  127. gcTicker := time.NewTicker(gcInterval)
  128. defer gcTicker.Stop()
  129. for {
  130. select {
  131. case now := <-gcTicker.C:
  132. for pid, c := range r.containersByPid {
  133. cg, err := proc.ReadCgroup(pid)
  134. if err != nil {
  135. delete(r.containersByPid, pid)
  136. if c != nil {
  137. c.onProcessExit(pid, false)
  138. }
  139. continue
  140. }
  141. if c != nil && cg.Id != c.cgroup.Id {
  142. delete(r.containersByPid, pid)
  143. c.onProcessExit(pid, false)
  144. }
  145. }
  146. activeIPs := map[netaddr.IP]struct{}{}
  147. for id, c := range r.containersById {
  148. for dst := range c.connectLastAttempt {
  149. activeIPs[dst.IP()] = struct{}{}
  150. }
  151. if !c.Dead(now) {
  152. continue
  153. }
  154. klog.Infoln("deleting dead container:", id)
  155. for cg, cc := range r.containersByCgroupId {
  156. if cc == c {
  157. delete(r.containersByCgroupId, cg)
  158. }
  159. }
  160. for pid, cc := range r.containersByPid {
  161. if cc == c {
  162. delete(r.containersByPid, pid)
  163. }
  164. }
  165. if ok := prometheus.WrapRegistererWith(prometheus.Labels{"container_id": string(id)}, r.reg).Unregister(c); !ok {
  166. klog.Warningln("failed to unregister container:", id)
  167. }
  168. delete(r.containersById, id)
  169. c.Close()
  170. }
  171. r.ip2fqdnLock.Lock()
  172. for ip := range r.ip2fqdn {
  173. if _, ok := activeIPs[ip]; !ok {
  174. delete(r.ip2fqdn, ip)
  175. }
  176. }
  177. r.ip2fqdnLock.Unlock()
  178. case u := <-r.trafficStatsUpdateCh:
  179. if u == nil {
  180. continue
  181. }
  182. if c := r.containersByPid[u.Pid]; c != nil {
  183. c.updateTrafficStats(u)
  184. }
  185. case e, more := <-ch:
  186. if !more {
  187. return
  188. }
  189. switch e.Type {
  190. case ebpftracer.EventTypeProcessStart:
  191. c, seen := r.containersByPid[e.Pid]
  192. switch { // possible pids wraparound + missed `process-exit` event
  193. case c == nil && seen: // ignored
  194. delete(r.containersByPid, e.Pid)
  195. case c != nil: // revalidating by cgroup
  196. cg, err := proc.ReadCgroup(e.Pid)
  197. if err != nil || cg.Id != c.cgroup.Id {
  198. delete(r.containersByPid, e.Pid)
  199. c.onProcessExit(e.Pid, false)
  200. }
  201. }
  202. if c := r.getOrCreateContainer(e.Pid); c != nil {
  203. p := c.onProcessStart(e.Pid)
  204. if r.processInfoCh != nil && p != nil {
  205. r.processInfoCh <- ProcessInfo{Pid: p.Pid, ContainerId: c.id, StartedAt: p.StartedAt}
  206. }
  207. }
  208. case ebpftracer.EventTypeProcessExit:
  209. if c := r.containersByPid[e.Pid]; c != nil {
  210. c.onProcessExit(e.Pid, e.Reason == ebpftracer.EventReasonOOMKill)
  211. }
  212. delete(r.containersByPid, e.Pid)
  213. case ebpftracer.EventTypeFileOpen:
  214. if c := r.getOrCreateContainer(e.Pid); c != nil {
  215. c.onFileOpen(e.Pid, e.Fd)
  216. }
  217. case ebpftracer.EventTypeListenOpen:
  218. if c := r.getOrCreateContainer(e.Pid); c != nil {
  219. c.onListenOpen(e.Pid, e.SrcAddr, false)
  220. } else {
  221. klog.Infoln("TCP listen open from unknown container", e)
  222. }
  223. case ebpftracer.EventTypeListenClose:
  224. if c := r.containersByPid[e.Pid]; c != nil {
  225. c.onListenClose(e.Pid, e.SrcAddr)
  226. }
  227. case ebpftracer.EventTypeConnectionOpen:
  228. if c := r.getOrCreateContainer(e.Pid); c != nil {
  229. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false, e.Duration)
  230. c.attachTlsUprobes(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, e.Duration)
  237. } else {
  238. klog.Infoln("TCP connection error from unknown container", e)
  239. }
  240. case ebpftracer.EventTypeConnectionClose:
  241. if c := r.containersByPid[e.Pid]; c != nil {
  242. c.onConnectionClose(e)
  243. }
  244. case ebpftracer.EventTypeTCPRetransmit:
  245. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  246. for _, c := range r.containersById {
  247. if c.onRetransmission(srcDst) {
  248. break
  249. }
  250. }
  251. case ebpftracer.EventTypeL7Request:
  252. if e.L7Request == nil {
  253. continue
  254. }
  255. if c := r.containersByPid[e.Pid]; c != nil {
  256. ip2fqdn := c.onL7Request(e.Pid, e.Fd, e.Timestamp, e.L7Request)
  257. r.ip2fqdnLock.Lock()
  258. for ip, fqdn := range ip2fqdn {
  259. r.ip2fqdn[ip] = fqdn
  260. }
  261. r.ip2fqdnLock.Unlock()
  262. }
  263. case ebpftracer.EventTypePythonThreadLock:
  264. if c := r.containersByPid[e.Pid]; c != nil {
  265. c.pythonThreadLockWaitTime += e.Duration
  266. }
  267. }
  268. }
  269. }
  270. }
  271. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  272. if c, seen := r.containersByPid[pid]; c != nil {
  273. return c
  274. } else if seen { // ignored
  275. return nil
  276. }
  277. cg, err := proc.ReadCgroup(pid)
  278. if err != nil {
  279. if !common.IsNotExist(err) {
  280. klog.Warningln("failed to read proc cgroup:", err)
  281. }
  282. return nil
  283. }
  284. if c := r.containersByCgroupId[cg.Id]; c != nil {
  285. r.containersByPid[pid] = c
  286. return c
  287. }
  288. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  289. cmdline := proc.GetCmdline(pid)
  290. parts := bytes.Split(cmdline, []byte{0})
  291. if len(parts) > 0 {
  292. cmd := parts[0]
  293. lastArg := parts[len(parts)-1]
  294. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  295. cg.ContainerId = string(lastArg)
  296. }
  297. }
  298. }
  299. md, err := getContainerMetadata(cg)
  300. if err != nil {
  301. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  302. return nil
  303. }
  304. id := calcId(cg, md)
  305. klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  306. if id == "" {
  307. if cg.Id == "/init.scope" && pid != 1 {
  308. klog.InfoS("ignoring without persisting", "cg", cg.Id, "pid", pid)
  309. } else {
  310. klog.InfoS("ignoring", "cg", cg.Id, "pid", pid)
  311. r.containersByPid[pid] = nil
  312. }
  313. return nil
  314. }
  315. if c := r.containersById[id]; c != nil {
  316. klog.Warningln("id conflict:", id)
  317. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  318. c.cgroup = cg
  319. c.metadata = md
  320. c.runLogParser("")
  321. if c.nsConntrack != nil {
  322. _ = c.nsConntrack.Close()
  323. c.nsConntrack = nil
  324. }
  325. }
  326. r.containersByPid[pid] = c
  327. r.containersByCgroupId[cg.Id] = c
  328. return c
  329. }
  330. c, err := NewContainer(id, cg, md, r.hostConntrack, pid, r)
  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. if err := prometheus.WrapRegistererWith(prometheus.Labels{"container_id": string(id)}, r.reg).Register(c); err != nil {
  337. klog.Warningln("failed to register container:", err)
  338. return nil
  339. }
  340. r.containersByPid[pid] = c
  341. r.containersByCgroupId[cg.Id] = c
  342. r.containersById[id] = c
  343. return c
  344. }
  345. func (r *Registry) updateTrafficStatsIfNecessary() {
  346. r.trafficStatsLock.Lock()
  347. defer r.trafficStatsLock.Unlock()
  348. if time.Now().Sub(r.trafficStatsLastUpdated) < MinTrafficStatsUpdateInterval {
  349. return
  350. }
  351. iter := r.tracer.ActiveConnectionsIterator()
  352. cid := ebpftracer.ConnectionId{}
  353. stats := ebpftracer.Connection{}
  354. for iter.Next(&cid, &stats) {
  355. r.trafficStatsUpdateCh <- &TrafficStatsUpdate{
  356. Pid: cid.PID,
  357. FD: cid.FD,
  358. BytesSent: stats.BytesSent,
  359. BytesReceived: stats.BytesReceived,
  360. }
  361. }
  362. if err := iter.Err(); err != nil {
  363. klog.Warningln(err)
  364. }
  365. r.trafficStatsUpdateCh <- nil
  366. r.trafficStatsLastUpdated = time.Now()
  367. }
  368. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata) ContainerID {
  369. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  370. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  371. return ""
  372. }
  373. return ContainerID(cg.ContainerId)
  374. }
  375. switch cg.ContainerType {
  376. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  377. default:
  378. return ""
  379. }
  380. if cg.ContainerId == "" {
  381. return ""
  382. }
  383. if md.labels["io.kubernetes.pod.name"] != "" {
  384. pod := md.labels["io.kubernetes.pod.name"]
  385. namespace := md.labels["io.kubernetes.pod.namespace"]
  386. name := md.labels["io.kubernetes.container.name"]
  387. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  388. name = "sandbox"
  389. }
  390. if name == "" || name == "POD" { // skip pause containers
  391. return ""
  392. }
  393. if g := cronjobPodName.FindStringSubmatch(pod); len(g) == 3 {
  394. now := time.Now()
  395. tsMiniutes, _ := strconv.ParseUint(g[2], 10, 64)
  396. scheduledAt := time.Unix(int64(tsMiniutes)*60, 0)
  397. if scheduledAt.After(now.Add(-cronjobPodScheduleWindow)) && scheduledAt.Before(now.Add(cronjobPodScheduleWindow)) {
  398. return ContainerID(fmt.Sprintf("/k8s-cronjob/%s/%s/%s", namespace, g[1], name))
  399. }
  400. }
  401. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name))
  402. }
  403. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  404. namespace := md.labels["com.docker.stack.namespace"]
  405. service := md.labels["com.docker.swarm.service.name"]
  406. if namespace != "" {
  407. service = strings.TrimPrefix(service, namespace+"_")
  408. }
  409. if namespace == "" {
  410. namespace = "_"
  411. }
  412. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1]))
  413. }
  414. if md.env != nil {
  415. allocId := md.env["NOMAD_ALLOC_ID"]
  416. group := md.env["NOMAD_GROUP_NAME"]
  417. job := md.env["NOMAD_JOB_NAME"]
  418. namespace := md.env["NOMAD_NAMESPACE"]
  419. task := md.env["NOMAD_TASK_NAME"]
  420. if allocId != "" && group != "" && job != "" && namespace != "" && task != "" {
  421. return ContainerID(fmt.Sprintf("/nomad/%s/%s/%s/%s/%s", namespace, job, group, allocId, task))
  422. }
  423. }
  424. if md.name == "" { // should be "pure" dockerd container here
  425. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  426. return ""
  427. }
  428. return ContainerID("/docker/" + md.name)
  429. }
  430. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  431. switch cg.ContainerType {
  432. case cgroup.ContainerTypeSystemdService:
  433. md := &ContainerMetadata{}
  434. md.systemdTriggeredBy = SystemdTriggeredBy(cg.ContainerId)
  435. return md, nil
  436. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  437. default:
  438. return &ContainerMetadata{}, nil
  439. }
  440. if cg.ContainerId == "" {
  441. return &ContainerMetadata{}, nil
  442. }
  443. if cg.ContainerType == cgroup.ContainerTypeCrio {
  444. return CrioInspect(cg.ContainerId)
  445. }
  446. var dockerdErr error
  447. if dockerdClient != nil {
  448. md, err := DockerdInspect(cg.ContainerId)
  449. if err == nil {
  450. return md, nil
  451. }
  452. dockerdErr = err
  453. }
  454. var containerdErr error
  455. if containerdClient != nil {
  456. md, err := ContainerdInspect(cg.ContainerId)
  457. if err == nil {
  458. return md, nil
  459. }
  460. containerdErr = err
  461. }
  462. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  463. }
  464. type TrafficStatsUpdate struct {
  465. Pid uint32
  466. FD uint64
  467. BytesSent uint64
  468. BytesReceived uint64
  469. }