registry.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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), // TODO: 队列
  86. hostConntrack: ct,
  87. containersById: map[ContainerID]*Container{}, // TODO: 缓存的一些关系映射
  88. containersByCgroupId: map[string]*Container{},
  89. containersByPid: map[uint32]*Container{},
  90. ip2fqdn: map[netaddr.IP]string{},
  91. processInfoCh: processInfoCh, // TODO: 进程信息
  92. tracer: ebpftracer.NewTracer(kernelVersion, *flags.DisableL7Tracing), // TODO: 核心代码
  93. }
  94. if err = reg.Register(r); err != nil {
  95. return nil, err
  96. }
  97. go r.handleEvents(r.events) // TODO: 核心代码
  98. if err = r.tracer.Run(r.events); err != nil { // TODO: 核心代码
  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: // TODO: 周期性做一些操作, 暂时忽略......
  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() // T
  174. case e, more := <-ch: // TODO: 核心代码, 读取chan中的数据.... 来自tracer.init方法...
  175. if e.Pid == uint32(os.Getpid()) {
  176. continue
  177. }
  178. //if e.Pid != 362943 { // TODO: TEST_DEBUG........只拦截一个进程.....
  179. // continue
  180. //}
  181. if !more {
  182. return
  183. }
  184. // fmt.Println("--------- <- ch -------------pid = ", e.Pid)
  185. switch e.Type {
  186. case ebpftracer.EventTypeProcessStart: // TODO: ??????
  187. // fmt.Println("----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) // TODO: 没有什么权限?
  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: // TODO: 核心逻辑:attachTlsUprobes, , 为什么放在这里???根据事件绑定uprobe???
  215. fmt.Println("ebpftracer.EventTypeConnectionOpen==================", e.Pid) // ebpftracer.EventTypeConnectionOpen================== 362943
  216. // fmt.Println("----EventTypeListenOpen----")
  217. if c := r.getOrCreateContainer(e.Pid); c != nil {
  218. c.onListenOpen(e.Pid, e.SrcAddr, false)
  219. c.attachTlsUprobes(r.tracer, e.Pid)
  220. } else {
  221. klog.Infoln("TCP listen open from unknown container", e)
  222. }
  223. case ebpftracer.EventTypeListenClose:
  224. // fmt.Println("----EventTypeListenClose----")
  225. if c := r.containersByPid[e.Pid]; c != nil {
  226. c.onListenClose(e.Pid, e.SrcAddr)
  227. }
  228. case ebpftracer.EventTypeConnectionOpen: // TODO: 核心逻辑:attachTlsUprobes, 为什么放在这里??? 根据事件绑定uprobe???
  229. // fmt.Println("----EventTypeConnectionOpen----")
  230. fmt.Println("ebpftracer.EventTypeConnectionOpen==================", e.Pid)
  231. if c := r.getOrCreateContainer(e.Pid); c != nil {
  232. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false)
  233. c.attachTlsUprobes(r.tracer, e.Pid)
  234. } else {
  235. klog.Infoln("TCP connection from unknown container", e)
  236. }
  237. case ebpftracer.EventTypeConnectionError:
  238. // fmt.Println("----EventTypeConnectionError----")
  239. if c := r.getOrCreateContainer(e.Pid); c != nil {
  240. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, 0, true)
  241. } else {
  242. klog.Infoln("TCP connection error from unknown container", e)
  243. }
  244. case ebpftracer.EventTypeConnectionClose:
  245. // fmt.Println("----EventTypeConnectionClose----")
  246. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  247. for _, c := range r.containersById {
  248. if c.onConnectionClose(srcDst) {
  249. break
  250. }
  251. }
  252. case ebpftracer.EventTypeTCPRetransmit:
  253. // fmt.Println("----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: // TODO: 核心代码, 处理7层协议请求, 来自tracer.runEventsReader方法......
  261. // fmt.Println("-----EventTypeL7Request------1", e) // TODO: 需要区分是client还是server吗?
  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. fmt.Println("-----EventTypeL7Request------2")
  268. ip2fqdn := c.onL7RequestApm(e.Pid, e.Fd, e.Timestamp, e.L7Request) // TODO: 核心代码
  269. r.ip2fqdnLock.Lock()
  270. for ip, fqdn := range ip2fqdn {
  271. r.ip2fqdn[ip] = fqdn
  272. }
  273. r.ip2fqdnLock.Unlock()
  274. }
  275. }
  276. }
  277. }
  278. }
  279. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  280. if c, seen := r.containersByPid[pid]; c != nil {
  281. return c
  282. } else if seen { // ignored
  283. return nil
  284. }
  285. cg, err := proc.ReadCgroup(pid)
  286. if err != nil {
  287. if !common.IsNotExist(err) {
  288. klog.Warningln("failed to read proc cgroup:", err)
  289. }
  290. return nil
  291. }
  292. cgId := fmt.Sprintf("%s/%d", cg.Id, pid)
  293. if c := r.containersByCgroupId[cgId]; c != nil {
  294. r.containersByPid[pid] = c
  295. return c
  296. }
  297. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  298. cmdline := proc.GetCmdline(pid)
  299. parts := bytes.Split(cmdline, []byte{0})
  300. if len(parts) > 0 {
  301. cmd := parts[0]
  302. lastArg := parts[len(parts)-1]
  303. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  304. cg.ContainerId = string(lastArg)
  305. }
  306. }
  307. }
  308. md, err := getContainerMetadata(cg)
  309. if err != nil {
  310. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  311. return nil
  312. }
  313. // add ns/workload/podname
  314. id, extensionTag := calcId(cg, md, pid)
  315. //klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  316. if id == "" {
  317. if cg.Id == "/init.scope" && pid != 1 {
  318. klog.InfoS("ignoring without persisting", "cg", cg.Id, "pid", pid)
  319. } else {
  320. klog.InfoS("ignoring", "cg", cg.Id, "pid", pid)
  321. r.containersByPid[pid] = nil
  322. }
  323. return nil
  324. }
  325. if c := r.containersById[id]; c != nil {
  326. klog.Warningln("id conflict:", id)
  327. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  328. c.cgroup = cg
  329. c.metadata = md
  330. c.runLogParser("")
  331. if c.nsConntrack != nil {
  332. _ = c.nsConntrack.Close()
  333. c.nsConntrack = nil
  334. }
  335. }
  336. setK8sTag(c, extensionTag, pid)
  337. r.containersByPid[pid] = c
  338. r.containersByCgroupId[cgId] = c
  339. return c
  340. }
  341. c, err := NewContainer(id, cg, md, r.hostConntrack, pid)
  342. if err != nil {
  343. klog.Warningf("failed to create container pid=%d cg=%s id=%s: %s", pid, cg.Id, id, err)
  344. return nil
  345. }
  346. //klog.InfoS("detected a new container", "pid", pid, "cg", cg.Id, "id", id)
  347. // add ns/workload/podname/pid/ctype
  348. //sType := fmt.Sprintf("%d", cg.ContainerType)
  349. setK8sTag(c, extensionTag, pid)
  350. if err := prometheus.WrapRegistererWith(setLabels(string(id),
  351. extensionTag[Namespace],
  352. extensionTag[PodName],
  353. extensionTag[ProcessName],
  354. fmt.Sprintf("%d", pid)), r.reg).Register(c); err != nil {
  355. klog.Warningln("failed to register container:", err)
  356. return nil
  357. }
  358. r.containersByPid[pid] = c
  359. r.containersByCgroupId[cgId] = c
  360. r.containersById[id] = c
  361. return c
  362. }
  363. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata, pid uint32) (ContainerID, map[string]string) {
  364. extensionTag := map[string]string{Namespace: "", Workload: "", PodName: "", ProcessName: ""}
  365. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  366. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  367. return "", extensionTag
  368. }
  369. return ContainerID(cg.ContainerId), extensionTag
  370. }
  371. if cg.ContainerType == cgroup.ContainerTypeStandaloneProcess {
  372. procName := proc.GetProcName(pid)
  373. extensionTag[ProcessName] = procName
  374. return ContainerID(fmt.Sprintf("/%s/%s/%d", "standalone", proc.GetProcName(pid), pid)), extensionTag
  375. }
  376. switch cg.ContainerType {
  377. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  378. default:
  379. return "", extensionTag
  380. }
  381. if cg.ContainerId == "" {
  382. return "", extensionTag
  383. }
  384. if md.labels["io.kubernetes.pod.name"] != "" {
  385. pod := md.labels["io.kubernetes.pod.name"]
  386. namespace := md.labels["io.kubernetes.pod.namespace"]
  387. name := md.labels["io.kubernetes.container.name"]
  388. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  389. name = "sandbox"
  390. }
  391. if name == "" || name == "POD" { // skip pause containers
  392. return "", extensionTag
  393. }
  394. extensionTag[Namespace] = namespace
  395. extensionTag[Workload] = ""
  396. extensionTag[PodName] = pod
  397. extensionTag[ProcessName] = name
  398. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name)), extensionTag
  399. }
  400. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  401. namespace := md.labels["com.docker.stack.namespace"]
  402. service := md.labels["com.docker.swarm.service.name"]
  403. if namespace != "" {
  404. service = strings.TrimPrefix(service, namespace+"_")
  405. }
  406. if namespace == "" {
  407. namespace = "_"
  408. }
  409. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1])), extensionTag
  410. }
  411. if md.name == "" { // should be "pure" dockerd container here
  412. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  413. return "", extensionTag
  414. }
  415. return ContainerID("/docker/" + md.name), extensionTag
  416. }
  417. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  418. switch cg.ContainerType {
  419. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  420. default:
  421. return &ContainerMetadata{}, nil
  422. }
  423. if cg.ContainerId == "" {
  424. return &ContainerMetadata{}, nil
  425. }
  426. if cg.ContainerType == cgroup.ContainerTypeCrio {
  427. return CrioInspect(cg.ContainerId)
  428. }
  429. var dockerdErr error
  430. if dockerdClient != nil {
  431. md, err := DockerdInspect(cg.ContainerId)
  432. if err == nil {
  433. return md, nil
  434. }
  435. dockerdErr = err
  436. }
  437. var containerdErr error
  438. if containerdClient != nil {
  439. md, err := ContainerdInspect(cg.ContainerId)
  440. if err == nil {
  441. return md, nil
  442. }
  443. containerdErr = err
  444. }
  445. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  446. }