registry.go 16 KB

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