registry.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  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/kube"
  12. . "github.com/coroot/coroot-node-agent/utils"
  13. "github.com/coroot/coroot-node-agent/utils/enums"
  14. . "github.com/coroot/coroot-node-agent/utils/modelse"
  15. "github.com/coroot/coroot-node-agent/utils/try"
  16. . "github.com/coroot/coroot-node-agent/utils/worker"
  17. "github.com/coroot/coroot-node-agent/cgroup"
  18. "github.com/coroot/coroot-node-agent/common"
  19. "github.com/coroot/coroot-node-agent/ebpftracer"
  20. "github.com/coroot/coroot-node-agent/ebpftracer/tracer"
  21. "github.com/coroot/coroot-node-agent/flags"
  22. "github.com/coroot/coroot-node-agent/proc"
  23. "github.com/prometheus/client_golang/prometheus"
  24. klog "github.com/sirupsen/logrus"
  25. "github.com/vishvananda/netns"
  26. "inet.af/netaddr"
  27. )
  28. const MinTrafficStatsUpdateInterval = 5 * time.Second
  29. var (
  30. selfNetNs = netns.None()
  31. hostNetNsId = netns.None().UniqueId()
  32. agentPid = uint32(os.Getpid())
  33. containerIdRegexp = regexp.MustCompile(`[a-z0-9]{64}`)
  34. cronjobPodName = regexp.MustCompile(`([a-z0-9-]+)-([0-9]{8})-[bcdfghjklmnpqrstvwxz2456789]{5}`)
  35. cronjobPodScheduleWindow = 7 * 24 * time.Hour
  36. )
  37. const OPEN_STACK = 1
  38. type ProcessInfo struct {
  39. Pid uint32
  40. ContainerId ContainerID
  41. StartedAt time.Time
  42. }
  43. type Registry struct {
  44. reg prometheus.Registerer
  45. tracer *ebpftracer.Tracer
  46. events chan ebpftracer.Event
  47. hostConntrack *Conntrack
  48. containersById map[ContainerID]*Container
  49. containersByCgroupId map[string]*Container
  50. containersByPid map[uint32]*Container
  51. ip2fqdn map[netaddr.IP]string
  52. ip2fqdnLock sync.Mutex
  53. processInfoCh chan<- ProcessInfo
  54. whiteListRules WhiteListMap
  55. whiteLastUpdatedTime int
  56. connServer ServerWorker
  57. trafficStatsLastUpdated time.Time
  58. trafficStatsLock sync.Mutex
  59. trafficStatsUpdateCh chan *TrafficStatsUpdate
  60. nodeInfo *NodeInfoT
  61. isFusing bool
  62. IsFuseException bool
  63. }
  64. var (
  65. uprobes []tracer.Uprobe
  66. uprobesMap map[string]tracer.Uprobe
  67. )
  68. func NewRegistry(reg prometheus.Registerer, kernelVersion string, nodeInfo *NodeInfoT, processInfoCh chan<- ProcessInfo) (*Registry, error) {
  69. ns, err := proc.GetSelfNetNs()
  70. if err != nil {
  71. return nil, err
  72. }
  73. selfNetNs = ns
  74. hostNetNs, err := proc.GetHostNetNs()
  75. if err != nil {
  76. return nil, err
  77. }
  78. defer hostNetNs.Close()
  79. hostNetNsId = hostNetNs.UniqueId()
  80. err = proc.ExecuteInNetNs(hostNetNs, selfNetNs, func() error {
  81. if err := TaskstatsInit(); err != nil {
  82. return err
  83. }
  84. return nil
  85. })
  86. if err != nil {
  87. return nil, err
  88. }
  89. if err := cgroup.Init(); err != nil {
  90. return nil, err
  91. }
  92. if err := DockerdInit(); err != nil {
  93. klog.Warningln(err)
  94. }
  95. if err := ContainerdInit(); err != nil {
  96. klog.Warningln(err)
  97. }
  98. if err := CrioInit(); err != nil {
  99. klog.Warningln(err)
  100. }
  101. if err := JournaldInit(); err != nil {
  102. klog.Warningln(err)
  103. }
  104. ct, err := NewConntrack(hostNetNs)
  105. if err != nil {
  106. return nil, err
  107. }
  108. r := &Registry{
  109. reg: reg,
  110. events: make(chan ebpftracer.Event, 10000),
  111. hostConntrack: ct,
  112. containersById: map[ContainerID]*Container{},
  113. containersByCgroupId: map[string]*Container{},
  114. containersByPid: map[uint32]*Container{},
  115. ip2fqdn: map[netaddr.IP]string{},
  116. processInfoCh: processInfoCh,
  117. tracer: ebpftracer.NewTracer(kernelVersion, *flags.DisableL7Tracing, *flags.DisableE2ETracing, *flags.DisableStackTracing),
  118. whiteListRules: make(WhiteListMap),
  119. trafficStatsUpdateCh: make(chan *TrafficStatsUpdate),
  120. nodeInfo: nodeInfo,
  121. }
  122. // 初始化软负载集群节点
  123. proxyClient, clientErr := NewProxyClient(*flags.ConfigServer, false)
  124. if clientErr == nil {
  125. // 负载健康检测
  126. try.Go(proxyClient.CheckEndpoints, CatchFn)
  127. klog.Infof("New Proxy Client success.config_server is [%s]", *flags.ConfigServer)
  128. } else {
  129. klog.WithError(clientErr).Errorf("NewProxyClient error, Please check [export CONFIG_ENDPOINT=ip:port]")
  130. return nil, clientErr
  131. }
  132. r.connServer, err = NewServerHTTPWorker()
  133. if err != nil {
  134. klog.Errorf("init connServer error:%s.", err)
  135. return nil, err
  136. }
  137. if !*flags.DisableRegisterHost {
  138. // Register Host
  139. err = r.RegisterHost()
  140. if err != nil {
  141. klog.WithError(err).Errorf("Failed Register Host.")
  142. return nil, err
  143. }
  144. try.Go(r.TaskRegisterHost, CatchFn)
  145. }
  146. if err = reg.Register(r); err != nil {
  147. return nil, err
  148. }
  149. //_, err = r.getWhiteList()
  150. //if err != nil {
  151. // return nil, err
  152. //}
  153. try.Go(r.PullAllAppInfo, CatchFn)
  154. go r.handleEvents(r.events)
  155. if err = r.tracer.Run(r.events); err != nil {
  156. close(r.events)
  157. return nil, err
  158. }
  159. return r, nil
  160. }
  161. func (r *Registry) Describe(ch chan<- *prometheus.Desc) {
  162. ch <- metrics.Ip2Fqdn
  163. }
  164. func (r *Registry) Collect(ch chan<- prometheus.Metric) {
  165. r.ip2fqdnLock.Lock()
  166. defer r.ip2fqdnLock.Unlock()
  167. for ip, fqdn := range r.ip2fqdn {
  168. ch <- gauge(metrics.Ip2Fqdn, 1, ip.String(), fqdn)
  169. }
  170. }
  171. func (r *Registry) Close() {
  172. r.tracer.Close()
  173. close(r.events)
  174. }
  175. func (r *Registry) handleEvents(ch <-chan ebpftracer.Event) {
  176. gcTicker := time.NewTicker(gcInterval)
  177. defer gcTicker.Stop()
  178. var fuseOnce bool
  179. for {
  180. select {
  181. case now := <-gcTicker.C:
  182. //_, err1 := os.Stat("/tmp/fuse")
  183. //if err1 == nil {
  184. // r.isFusing = true
  185. //} else {
  186. // r.isFusing = false
  187. //}
  188. //_, err := r.pullWhiteList()
  189. _, err := r.pullWhiteListV2()
  190. if err != nil {
  191. klog.WithError(err).Errorf("connWhiteList error")
  192. }
  193. runtimeApps := make(map[uint32]AppStatusInfo)
  194. for pid, c := range r.containersByPid {
  195. if c != nil && !common.IsOpenFilter() && !fuseOnce {
  196. c.AgentCtrl(r, pid)
  197. }
  198. c.BuildActiveApps(runtimeApps, pid)
  199. cg, err := proc.ReadCgroup(pid)
  200. if err != nil {
  201. delete(r.containersByPid, pid)
  202. if c != nil {
  203. c.onProcessExit(pid, false)
  204. }
  205. continue
  206. }
  207. if c != nil && cg.Id != c.cgroup.Id {
  208. delete(r.containersByPid, pid)
  209. c.onProcessExit(pid, false)
  210. }
  211. }
  212. saveAppInfo(runtimeApps)
  213. if r.isFusing {
  214. fuseOnce = true
  215. } else {
  216. fuseOnce = false
  217. }
  218. activeIPs := map[netaddr.IP]struct{}{}
  219. for id, c := range r.containersById {
  220. for dst := range c.connectLastAttempt {
  221. activeIPs[dst.IP()] = struct{}{}
  222. }
  223. if !c.Dead(now) {
  224. continue
  225. }
  226. klog.Infoln("deleting dead container:", id)
  227. for cg, cc := range r.containersByCgroupId {
  228. if cc == c {
  229. delete(r.containersByCgroupId, cg)
  230. }
  231. }
  232. for pid, cc := range r.containersByPid {
  233. if cc == c {
  234. delete(r.containersByPid, pid)
  235. }
  236. }
  237. if ok := prometheus.WrapRegistererWith(setLabels(string(id),
  238. c.K8sContainer.ns,
  239. c.K8sContainer.workload,
  240. c.K8sContainer.podName,
  241. c.K8sContainer.containerName,
  242. c.K8sContainer.pid), r.reg).Unregister(c); !ok {
  243. klog.Warningln("failed to unregister container:", id)
  244. }
  245. delete(r.containersById, id)
  246. c.Close()
  247. }
  248. r.ip2fqdnLock.Lock()
  249. for ip := range r.ip2fqdn {
  250. if _, ok := activeIPs[ip]; !ok {
  251. delete(r.ip2fqdn, ip)
  252. }
  253. }
  254. r.ip2fqdnLock.Unlock()
  255. case u := <-r.trafficStatsUpdateCh:
  256. if u == nil {
  257. continue
  258. }
  259. if c := r.containersByPid[u.Pid]; c != nil {
  260. c.updateTrafficStats(u)
  261. }
  262. case e, more := <-ch:
  263. if e.Pid == uint32(os.Getpid()) {
  264. continue
  265. }
  266. if !more {
  267. return
  268. }
  269. switch e.Type {
  270. case ebpftracer.EventTypeProcessStart:
  271. c, seen := r.containersByPid[e.Pid]
  272. switch { // possible pids wraparound + missed `process-exit` event
  273. case c == nil && seen: // ignored
  274. delete(r.containersByPid, e.Pid)
  275. case c != nil: // revalidating by cgroup
  276. cg, err := proc.ReadCgroup(e.Pid)
  277. if err != nil || cg.Id != c.cgroup.Id {
  278. delete(r.containersByPid, e.Pid)
  279. c.onProcessExit(e.Pid, false)
  280. }
  281. }
  282. if c := r.getOrCreateContainer(e.Pid); c != nil {
  283. p := c.onProcessStart(e.Pid)
  284. if r.processInfoCh != nil && p != nil {
  285. r.processInfoCh <- ProcessInfo{Pid: p.Pid, ContainerId: c.id, StartedAt: p.StartedAt}
  286. }
  287. }
  288. case ebpftracer.EventTypeProcessExit:
  289. if c := r.containersByPid[e.Pid]; c != nil {
  290. c.onProcessExit(e.Pid, e.Reason == ebpftracer.EventReasonOOMKill)
  291. }
  292. delete(r.containersByPid, e.Pid)
  293. case ebpftracer.EventTypeFileOpen:
  294. if c := r.getOrCreateContainer(e.Pid); c != nil {
  295. c.onFileOpen(e.Pid, e.Fd)
  296. }
  297. case ebpftracer.EventTypeListenOpen:
  298. //fmt.Println("ebpftracer.EventTypeListenOpen==================", e.Pid)
  299. if c := r.getOrCreateContainer(e.Pid); c != nil {
  300. c.onListenOpen(e.Pid, e.SrcAddr, false)
  301. // cmdline InstanceID agentID
  302. if !common.IsOpenFilter() || common.IsFilterPid(e.Pid) {
  303. if c.buildIDs(e.Pid) {
  304. c.eventReady()
  305. }
  306. }
  307. if common.IsOpenFilter() && common.IsFilterPid(e.Pid) {
  308. c.WhiteSettingInfo.AppName = enums.TestApp
  309. err := c.RegisterAppInfo(r, e.Pid)
  310. if err != nil {
  311. klog.WithError(err).Errorf("[registry] Failed registerAppInfo. pid is %d", e.Pid)
  312. continue
  313. }
  314. c.AttachUprobes(r.tracer, e.Pid)
  315. if !r.tracer.DisableStackTracing() {
  316. err = c.AttachStack(r.tracer, e.Pid)
  317. if err != nil {
  318. klog.WithField("pid", e.Pid).WithError(err).Errorf("[registry][end] Failed attach stack trace!")
  319. }
  320. }
  321. }
  322. } else {
  323. klog.Infoln("TCP listen open from unknown container", e)
  324. }
  325. case ebpftracer.EventTypeAcceptOpen:
  326. klog.Infoln("ebpftracer.EventTypeAcceptOpen==================", e.Pid)
  327. if c := r.getOrCreateContainer(e.Pid); c != nil {
  328. c.onAcceptOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false, e.Duration)
  329. c.eventReady()
  330. } else {
  331. klog.Infoln("TCP connection from unknown container", e)
  332. }
  333. case ebpftracer.EventTypeConnectionOpen:
  334. //fmt.Println("ebpftracer.EventTypeConnectionOpen==================", e.Pid)
  335. if c := r.getOrCreateContainer(e.Pid); c != nil {
  336. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false, e.Duration)
  337. if !common.IsOpenFilter() || common.IsFilterPid(e.Pid) {
  338. if !c.checkEventReady() && c.buildIDs(e.Pid) {
  339. c.eventReady()
  340. }
  341. }
  342. if common.IsOpenFilter() && common.IsFilterPid(e.Pid) {
  343. c.WhiteSettingInfo.AppName = enums.TestApp
  344. err := c.RegisterAppInfo(r, e.Pid)
  345. if err != nil {
  346. klog.WithError(err).Errorf("[registry] Failed registerAppInfo. pid is %d", e.Pid)
  347. continue
  348. }
  349. c.AttachUprobes(r.tracer, e.Pid)
  350. // 禁用stack
  351. if !r.tracer.DisableStackTracing() {
  352. err = c.AttachStack(r.tracer, e.Pid)
  353. if err != nil {
  354. klog.WithField("pid", e.Pid).WithError(err).Errorf("[registry][end] Failed attach stack trace!")
  355. }
  356. } else {
  357. klog.Warnf("StackTrace tracing is disabled")
  358. }
  359. }
  360. } else {
  361. klog.Infoln("TCP connection from unknown container", e)
  362. }
  363. case ebpftracer.EventTypeListenClose:
  364. if c := r.containersByPid[e.Pid]; c != nil {
  365. c.onListenClose(e.Pid, e.SrcAddr)
  366. }
  367. case ebpftracer.EventTypeConnectionError:
  368. if c := r.getOrCreateContainer(e.Pid); c != nil {
  369. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, 0, true, e.Duration)
  370. } else {
  371. klog.Infoln("TCP connection error from unknown container", e)
  372. }
  373. case ebpftracer.EventTypeConnectionClose:
  374. if c := r.containersByPid[e.Pid]; c != nil {
  375. c.onConnectionClose(e)
  376. }
  377. case ebpftracer.EventTypeAcceptClose:
  378. if c := r.containersByPid[e.Pid]; c != nil {
  379. c.onAcceptClose(e)
  380. }
  381. case ebpftracer.EventTypeTCPRetransmit:
  382. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  383. for _, c := range r.containersById {
  384. if c.onRetransmission(srcDst) {
  385. break
  386. }
  387. }
  388. case ebpftracer.EventTypeL7Request:
  389. //fmt.Println("e.L7Request Payload:", string(e.L7Request.Payload))
  390. if e.L7Request == nil {
  391. continue
  392. }
  393. if c := r.containersByPid[e.Pid]; c != nil {
  394. //fmt.Println("EventTypeL7Request", e.Pid, c.Isl7AttachSuccess())
  395. //a, _ := json.Marshal(e.L7Request)
  396. //fmt.Println("EventTypeL7Request", e.Pid, string(a))
  397. klog.Debugln("Payload:", string(e.L7Request.Payload))
  398. ip2fqdn := c.onL7RequestApm(e.Pid, e.Fd, e.Timestamp, e.L7Request)
  399. r.ip2fqdnLock.Lock()
  400. for ip, fqdn := range ip2fqdn {
  401. r.ip2fqdn[ip] = fqdn
  402. }
  403. r.ip2fqdnLock.Unlock()
  404. }
  405. case ebpftracer.EventTypeFunEnt:
  406. if e.StackEvent == nil {
  407. continue
  408. }
  409. if c := r.containersByPid[uint32(e.StackEvent.Pid)]; c != nil {
  410. if e.StackEvent.Type == uint64(CodeTypeJava) {
  411. klog.Debugf("e.EventTypeFunEnt: TraceId:%d, Pid:%d, Location:%d, Goid:%d, TimeNs:%d, Ip:%X, CallerIp:%d, Bp:%d, CallerBp:%d\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)
  412. klog.Debugf("e.EventTypeFunEnt: TraceId: MethedName: %d -- %s -- %s", e.StackEvent.Type, e.StackEvent.MethedName, e.StackEvent.ClassName)
  413. } else {
  414. klog.Debugf("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)
  415. }
  416. c.StackProcess2(*e.StackEvent, r.tracer)
  417. } else {
  418. // 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)
  419. // fmt.Printf("e.EventTypeFunEnt ErrorError: TraceId:%x, FPid:%x, Nid:%x, Level:%d\n", e.StackEvent.Fpid, e.StackEvent.Nid, e.StackEvent.Level)
  420. }
  421. }
  422. }
  423. }
  424. }
  425. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  426. if c, seen := r.containersByPid[pid]; c != nil {
  427. return c
  428. } else if seen { // ignored
  429. return nil
  430. }
  431. cg, err := proc.ReadCgroup(pid)
  432. if err != nil {
  433. if !common.IsNotExist(err) {
  434. klog.Warningln("failed to read proc cgroup:", err)
  435. }
  436. return nil
  437. }
  438. cgId := fmt.Sprintf("%s/%d", cg.Id, pid)
  439. if c := r.containersByCgroupId[cgId]; c != nil {
  440. r.containersByPid[pid] = c
  441. return c
  442. }
  443. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  444. cmdline := proc.GetCmdline(pid)
  445. parts := bytes.Split(cmdline, []byte{0})
  446. if len(parts) > 0 {
  447. cmd := parts[0]
  448. lastArg := parts[len(parts)-1]
  449. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  450. cg.ContainerId = string(lastArg)
  451. }
  452. }
  453. }
  454. md, err := getContainerMetadata(cg)
  455. if err != nil {
  456. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  457. return nil
  458. }
  459. // add ns/workload/podname
  460. id, extensionTag := calcId(cg, md, pid)
  461. //klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  462. if id == "" {
  463. if cg.Id == "/init.scope" && pid != 1 {
  464. klog.Infoln("ignoring without persisting", "cg", cg.Id, "pid", pid)
  465. } else {
  466. klog.Infoln("ignoring", "cg", cg.Id, "pid", pid)
  467. r.containersByPid[pid] = nil
  468. }
  469. return nil
  470. }
  471. if c := r.containersById[id]; c != nil {
  472. //klog.Warningln("id conflict:", id)
  473. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  474. c.cgroup = cg
  475. c.metadata = md
  476. c.runLogParser("")
  477. if c.nsConntrack != nil {
  478. _ = c.nsConntrack.Close()
  479. c.nsConntrack = nil
  480. }
  481. }
  482. setK8sTag(c, extensionTag, pid)
  483. r.containersByPid[pid] = c
  484. r.containersByCgroupId[cgId] = c
  485. return c
  486. }
  487. c, err := NewContainer(id, cg, md, r.hostConntrack, pid, r)
  488. if err != nil {
  489. klog.Warningf("failed to create container pid=%d cg=%s id=%s: %s", pid, cg.Id, id, err)
  490. return nil
  491. }
  492. //klog.Infoln("detected a new container", "pid", pid, "cg", cg.Id, "id", id)
  493. // add ns/workload/podname/pid/ctype
  494. //sType := fmt.Sprintf("%d", cg.ContainerType)
  495. setK8sTag(c, extensionTag, pid)
  496. if err := prometheus.WrapRegistererWith(setLabels(string(id),
  497. extensionTag[Namespace],
  498. extensionTag[Workload],
  499. extensionTag[PodName],
  500. extensionTag[ProcessName],
  501. fmt.Sprintf("%d", pid)), r.reg).Register(c); err != nil {
  502. klog.Warningln("failed to register container:", err)
  503. return nil
  504. }
  505. r.containersByPid[pid] = c
  506. r.containersByCgroupId[cgId] = c
  507. r.containersById[id] = c
  508. return c
  509. }
  510. func (r *Registry) updateTrafficStatsIfNecessary() {
  511. r.trafficStatsLock.Lock()
  512. defer r.trafficStatsLock.Unlock()
  513. if time.Now().Sub(r.trafficStatsLastUpdated) < MinTrafficStatsUpdateInterval {
  514. return
  515. }
  516. iter := r.tracer.ActiveConnectionsIterator()
  517. cid := ConnectionId{}
  518. stats := Connection{}
  519. for iter.Next(&cid, &stats) {
  520. r.trafficStatsUpdateCh <- &TrafficStatsUpdate{
  521. Pid: cid.PID,
  522. FD: cid.FD,
  523. BytesSent: stats.BytesSent,
  524. BytesReceived: stats.BytesReceived,
  525. }
  526. }
  527. if err := iter.Err(); err != nil {
  528. klog.Warningln(err)
  529. }
  530. r.trafficStatsUpdateCh <- nil
  531. r.trafficStatsLastUpdated = time.Now()
  532. }
  533. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata, pid uint32) (ContainerID, map[string]string) {
  534. // 卡一下防止概率性获取为bash
  535. time.Sleep(1 * time.Millisecond)
  536. procName := proc.GetProcName(pid)
  537. extensionTag := map[string]string{Namespace: "", Workload: "", PodName: "", ProcessName: procName}
  538. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  539. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  540. return "", extensionTag
  541. }
  542. return ContainerID(cg.ContainerId), extensionTag
  543. }
  544. if cg.ContainerType == cgroup.ContainerTypeStandaloneProcess {
  545. //extensionTag[ProcessName] = procName
  546. return ContainerID(fmt.Sprintf("/%s/%s/%d", "standalone", procName, pid)), extensionTag
  547. }
  548. switch cg.ContainerType {
  549. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  550. default:
  551. return "", extensionTag
  552. }
  553. if cg.ContainerId == "" {
  554. return "", extensionTag
  555. }
  556. if md.labels["io.kubernetes.pod.name"] != "" {
  557. pod := md.labels["io.kubernetes.pod.name"]
  558. namespace := md.labels["io.kubernetes.pod.namespace"]
  559. name := md.labels["io.kubernetes.container.name"]
  560. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  561. name = "sandbox"
  562. }
  563. if name == "" || name == "POD" { // skip pause containers
  564. return "", extensionTag
  565. }
  566. extensionTag[Namespace] = namespace
  567. if *flags.RunInContainer {
  568. extensionTag[Workload], _ = kube.GetWorkload(namespace, pod)
  569. }
  570. extensionTag[PodName] = pod
  571. //extensionTag[ProcessName] = name
  572. if g := cronjobPodName.FindStringSubmatch(pod); len(g) == 3 {
  573. now := time.Now()
  574. tsMiniutes, _ := strconv.ParseUint(g[2], 10, 64)
  575. scheduledAt := time.Unix(int64(tsMiniutes)*60, 0)
  576. if scheduledAt.After(now.Add(-cronjobPodScheduleWindow)) && scheduledAt.Before(now.Add(cronjobPodScheduleWindow)) {
  577. return ContainerID(fmt.Sprintf("/k8s-cronjob/%s/%s/%s", namespace, g[1], name)), extensionTag
  578. }
  579. }
  580. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name)), extensionTag
  581. }
  582. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  583. namespace := md.labels["com.docker.stack.namespace"]
  584. service := md.labels["com.docker.swarm.service.name"]
  585. if namespace != "" {
  586. service = strings.TrimPrefix(service, namespace+"_")
  587. }
  588. if namespace == "" {
  589. namespace = "_"
  590. }
  591. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1])), extensionTag
  592. }
  593. if md.env != nil {
  594. allocId := md.env["NOMAD_ALLOC_ID"]
  595. group := md.env["NOMAD_GROUP_NAME"]
  596. job := md.env["NOMAD_JOB_NAME"]
  597. namespace := md.env["NOMAD_NAMESPACE"]
  598. task := md.env["NOMAD_TASK_NAME"]
  599. if allocId != "" && group != "" && job != "" && namespace != "" && task != "" {
  600. return ContainerID(fmt.Sprintf("/nomad/%s/%s/%s/%s/%s", namespace, job, group, allocId, task)), extensionTag
  601. }
  602. }
  603. if md.name == "" { // should be "pure" dockerd container here
  604. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  605. return "", extensionTag
  606. }
  607. return ContainerID("/docker/" + md.name), extensionTag
  608. }
  609. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  610. switch cg.ContainerType {
  611. case cgroup.ContainerTypeSystemdService:
  612. md := &ContainerMetadata{}
  613. md.systemdTriggeredBy = SystemdTriggeredBy(cg.ContainerId)
  614. return md, nil
  615. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  616. default:
  617. return &ContainerMetadata{}, nil
  618. }
  619. if cg.ContainerId == "" {
  620. return &ContainerMetadata{}, nil
  621. }
  622. if cg.ContainerType == cgroup.ContainerTypeCrio {
  623. return CrioInspect(cg.ContainerId)
  624. }
  625. var dockerdErr error
  626. if dockerdClient != nil {
  627. md, err := DockerdInspect(cg.ContainerId)
  628. if err == nil {
  629. return md, nil
  630. }
  631. dockerdErr = err
  632. }
  633. var containerdErr error
  634. if containerdClient != nil {
  635. md, err := ContainerdInspect(cg.ContainerId)
  636. if err == nil {
  637. return md, nil
  638. }
  639. containerdErr = err
  640. }
  641. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  642. }
  643. type TrafficStatsUpdate struct {
  644. Pid uint32
  645. FD uint64
  646. BytesSent uint64
  647. BytesReceived uint64
  648. }
  649. func (r *Registry) IsFusing() bool {
  650. return r.isFusing
  651. }