registry.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693
  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. }
  145. if err = reg.Register(r); err != nil {
  146. return nil, err
  147. }
  148. //_, err = r.getWhiteList()
  149. //if err != nil {
  150. // return nil, err
  151. //}
  152. try.Go(r.PullAllAppInfo, CatchFn)
  153. go r.handleEvents(r.events)
  154. if err = r.tracer.Run(r.events); err != nil {
  155. close(r.events)
  156. return nil, err
  157. }
  158. return r, nil
  159. }
  160. func (r *Registry) Describe(ch chan<- *prometheus.Desc) {
  161. ch <- metrics.Ip2Fqdn
  162. }
  163. func (r *Registry) Collect(ch chan<- prometheus.Metric) {
  164. r.ip2fqdnLock.Lock()
  165. defer r.ip2fqdnLock.Unlock()
  166. for ip, fqdn := range r.ip2fqdn {
  167. ch <- gauge(metrics.Ip2Fqdn, 1, ip.String(), fqdn)
  168. }
  169. }
  170. func (r *Registry) Close() {
  171. r.tracer.Close()
  172. close(r.events)
  173. }
  174. func (r *Registry) handleEvents(ch <-chan ebpftracer.Event) {
  175. gcTicker := time.NewTicker(gcInterval)
  176. defer gcTicker.Stop()
  177. var fuseOnce bool
  178. for {
  179. select {
  180. case now := <-gcTicker.C:
  181. //_, err1 := os.Stat("/tmp/fuse")
  182. //if err1 == nil {
  183. // r.isFusing = true
  184. //} else {
  185. // r.isFusing = false
  186. //}
  187. //_, err := r.pullWhiteList()
  188. _, err := r.pullWhiteListV2()
  189. if err != nil {
  190. klog.WithError(err).Errorf("connWhiteList error")
  191. }
  192. runtimeApps := make(map[uint32]AppStatusInfo)
  193. for pid, c := range r.containersByPid {
  194. if c != nil && !common.IsOpenFilter() && !fuseOnce {
  195. c.AgentCtrl(r, pid)
  196. }
  197. c.BuildActiveApps(runtimeApps, pid)
  198. cg, err := proc.ReadCgroup(pid)
  199. if err != nil {
  200. delete(r.containersByPid, pid)
  201. if c != nil {
  202. c.onProcessExit(pid, false)
  203. }
  204. continue
  205. }
  206. if c != nil && cg.Id != c.cgroup.Id {
  207. delete(r.containersByPid, pid)
  208. c.onProcessExit(pid, false)
  209. }
  210. }
  211. saveAppInfo(runtimeApps)
  212. if r.isFusing {
  213. fuseOnce = true
  214. } else {
  215. fuseOnce = false
  216. }
  217. activeIPs := map[netaddr.IP]struct{}{}
  218. for id, c := range r.containersById {
  219. for dst := range c.connectLastAttempt {
  220. activeIPs[dst.IP()] = struct{}{}
  221. }
  222. if !c.Dead(now) {
  223. continue
  224. }
  225. klog.Infoln("deleting dead container:", id)
  226. for cg, cc := range r.containersByCgroupId {
  227. if cc == c {
  228. delete(r.containersByCgroupId, cg)
  229. }
  230. }
  231. for pid, cc := range r.containersByPid {
  232. if cc == c {
  233. delete(r.containersByPid, pid)
  234. }
  235. }
  236. if ok := prometheus.WrapRegistererWith(setLabels(string(id),
  237. c.K8sContainer.ns,
  238. c.K8sContainer.workload,
  239. c.K8sContainer.podName,
  240. c.K8sContainer.containerName,
  241. c.K8sContainer.pid), r.reg).Unregister(c); !ok {
  242. klog.Warningln("failed to unregister container:", id)
  243. }
  244. delete(r.containersById, id)
  245. c.Close()
  246. }
  247. r.ip2fqdnLock.Lock()
  248. for ip := range r.ip2fqdn {
  249. if _, ok := activeIPs[ip]; !ok {
  250. delete(r.ip2fqdn, ip)
  251. }
  252. }
  253. r.ip2fqdnLock.Unlock()
  254. case u := <-r.trafficStatsUpdateCh:
  255. if u == nil {
  256. continue
  257. }
  258. if c := r.containersByPid[u.Pid]; c != nil {
  259. c.updateTrafficStats(u)
  260. }
  261. case e, more := <-ch:
  262. if e.Pid == uint32(os.Getpid()) {
  263. continue
  264. }
  265. if !more {
  266. return
  267. }
  268. switch e.Type {
  269. case ebpftracer.EventTypeProcessStart:
  270. c, seen := r.containersByPid[e.Pid]
  271. switch { // possible pids wraparound + missed `process-exit` event
  272. case c == nil && seen: // ignored
  273. delete(r.containersByPid, e.Pid)
  274. case c != nil: // revalidating by cgroup
  275. cg, err := proc.ReadCgroup(e.Pid)
  276. if err != nil || cg.Id != c.cgroup.Id {
  277. delete(r.containersByPid, e.Pid)
  278. c.onProcessExit(e.Pid, false)
  279. }
  280. }
  281. if c := r.getOrCreateContainer(e.Pid); c != nil {
  282. p := c.onProcessStart(e.Pid)
  283. if r.processInfoCh != nil && p != nil {
  284. r.processInfoCh <- ProcessInfo{Pid: p.Pid, ContainerId: c.id, StartedAt: p.StartedAt}
  285. }
  286. }
  287. case ebpftracer.EventTypeProcessExit:
  288. if c := r.containersByPid[e.Pid]; c != nil {
  289. c.onProcessExit(e.Pid, e.Reason == ebpftracer.EventReasonOOMKill)
  290. }
  291. delete(r.containersByPid, e.Pid)
  292. case ebpftracer.EventTypeFileOpen:
  293. if c := r.getOrCreateContainer(e.Pid); c != nil {
  294. c.onFileOpen(e.Pid, e.Fd)
  295. }
  296. case ebpftracer.EventTypeListenOpen:
  297. //fmt.Println("ebpftracer.EventTypeListenOpen==================", e.Pid)
  298. if c := r.getOrCreateContainer(e.Pid); c != nil {
  299. c.onListenOpen(e.Pid, e.SrcAddr, false)
  300. // cmdline InstanceID agentID
  301. if !common.IsOpenFilter() || common.IsFilterPid(e.Pid) {
  302. if c.buildIDs(e.Pid) {
  303. c.eventReady()
  304. }
  305. }
  306. if common.IsOpenFilter() && common.IsFilterPid(e.Pid) {
  307. c.WhiteSettingInfo.AppName = enums.TestApp
  308. err := c.RegisterAppInfo(r, e.Pid)
  309. if err != nil {
  310. klog.WithError(err).Errorf("[registry] Failed registerAppInfo. pid is %d", e.Pid)
  311. continue
  312. }
  313. c.AttachUprobes(r.tracer, e.Pid)
  314. if !r.tracer.DisableStackTracing() {
  315. err = c.AttachStack(r.tracer, e.Pid)
  316. if err != nil {
  317. klog.WithField("pid", e.Pid).WithError(err).Errorf("[registry][end] Failed attach stack trace!")
  318. }
  319. }
  320. }
  321. } else {
  322. klog.Infoln("TCP listen open from unknown container", e)
  323. }
  324. case ebpftracer.EventTypeAcceptOpen:
  325. klog.Infoln("ebpftracer.EventTypeAcceptOpen==================", e.Pid)
  326. if c := r.getOrCreateContainer(e.Pid); c != nil {
  327. c.onAcceptOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false, e.Duration)
  328. c.eventReady()
  329. } else {
  330. klog.Infoln("TCP connection from unknown container", e)
  331. }
  332. case ebpftracer.EventTypeConnectionOpen:
  333. //fmt.Println("ebpftracer.EventTypeConnectionOpen==================", e.Pid)
  334. if c := r.getOrCreateContainer(e.Pid); c != nil {
  335. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false, e.Duration)
  336. if !common.IsOpenFilter() || common.IsFilterPid(e.Pid) {
  337. if !c.checkEventReady() && c.buildIDs(e.Pid) {
  338. c.eventReady()
  339. }
  340. }
  341. if common.IsOpenFilter() && common.IsFilterPid(e.Pid) {
  342. c.WhiteSettingInfo.AppName = enums.TestApp
  343. err := c.RegisterAppInfo(r, e.Pid)
  344. if err != nil {
  345. klog.WithError(err).Errorf("[registry] Failed registerAppInfo. pid is %d", e.Pid)
  346. continue
  347. }
  348. c.AttachUprobes(r.tracer, e.Pid)
  349. // 禁用stack
  350. if !r.tracer.DisableStackTracing() {
  351. err = c.AttachStack(r.tracer, e.Pid)
  352. if err != nil {
  353. klog.WithField("pid", e.Pid).WithError(err).Errorf("[registry][end] Failed attach stack trace!")
  354. }
  355. } else {
  356. klog.Warnf("StackTrace tracing is disabled")
  357. }
  358. }
  359. } else {
  360. klog.Infoln("TCP connection from unknown container", e)
  361. }
  362. case ebpftracer.EventTypeListenClose:
  363. if c := r.containersByPid[e.Pid]; c != nil {
  364. c.onListenClose(e.Pid, e.SrcAddr)
  365. }
  366. case ebpftracer.EventTypeConnectionError:
  367. if c := r.getOrCreateContainer(e.Pid); c != nil {
  368. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, 0, true, e.Duration)
  369. } else {
  370. klog.Infoln("TCP connection error from unknown container", e)
  371. }
  372. case ebpftracer.EventTypeConnectionClose:
  373. if c := r.containersByPid[e.Pid]; c != nil {
  374. c.onConnectionClose(e)
  375. }
  376. case ebpftracer.EventTypeAcceptClose:
  377. if c := r.containersByPid[e.Pid]; c != nil {
  378. c.onAcceptClose(e)
  379. }
  380. case ebpftracer.EventTypeTCPRetransmit:
  381. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  382. for _, c := range r.containersById {
  383. if c.onRetransmission(srcDst) {
  384. break
  385. }
  386. }
  387. case ebpftracer.EventTypeL7Request:
  388. //fmt.Println("e.L7Request Payload:", string(e.L7Request.Payload))
  389. if e.L7Request == nil {
  390. continue
  391. }
  392. if c := r.containersByPid[e.Pid]; c != nil {
  393. //fmt.Println("EventTypeL7Request", e.Pid, c.Isl7AttachSuccess())
  394. //a, _ := json.Marshal(e.L7Request)
  395. //fmt.Println("EventTypeL7Request", e.Pid, string(a))
  396. fmt.Println("e---.L7Request Payload:", string(e.L7Request.Payload))
  397. ip2fqdn := c.onL7RequestApm(e.Pid, e.Fd, e.Timestamp, e.L7Request)
  398. r.ip2fqdnLock.Lock()
  399. for ip, fqdn := range ip2fqdn {
  400. r.ip2fqdn[ip] = fqdn
  401. }
  402. r.ip2fqdnLock.Unlock()
  403. }
  404. case ebpftracer.EventTypeFunEnt:
  405. if e.StackEvent == nil {
  406. continue
  407. }
  408. if c := r.containersByPid[uint32(e.StackEvent.Pid)]; c != nil {
  409. if e.StackEvent.Type == uint64(CodeTypeJava) {
  410. fmt.Printf("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)
  411. fmt.Printf("e.EventTypeFunEnt: TraceId: MethedName: %d -- %s -- %s", e.StackEvent.Type, e.StackEvent.MethedName, e.StackEvent.ClassName)
  412. } else {
  413. 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)
  414. }
  415. c.StackProcess2(*e.StackEvent, r.tracer)
  416. } else {
  417. // 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)
  418. // fmt.Printf("e.EventTypeFunEnt ErrorError: TraceId:%x, FPid:%x, Nid:%x, Level:%d\n", e.StackEvent.Fpid, e.StackEvent.Nid, e.StackEvent.Level)
  419. }
  420. }
  421. }
  422. }
  423. }
  424. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  425. if c, seen := r.containersByPid[pid]; c != nil {
  426. return c
  427. } else if seen { // ignored
  428. return nil
  429. }
  430. cg, err := proc.ReadCgroup(pid)
  431. if err != nil {
  432. if !common.IsNotExist(err) {
  433. klog.Warningln("failed to read proc cgroup:", err)
  434. }
  435. return nil
  436. }
  437. cgId := fmt.Sprintf("%s/%d", cg.Id, pid)
  438. if c := r.containersByCgroupId[cgId]; c != nil {
  439. r.containersByPid[pid] = c
  440. return c
  441. }
  442. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  443. cmdline := proc.GetCmdline(pid)
  444. parts := bytes.Split(cmdline, []byte{0})
  445. if len(parts) > 0 {
  446. cmd := parts[0]
  447. lastArg := parts[len(parts)-1]
  448. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  449. cg.ContainerId = string(lastArg)
  450. }
  451. }
  452. }
  453. md, err := getContainerMetadata(cg)
  454. if err != nil {
  455. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  456. return nil
  457. }
  458. // add ns/workload/podname
  459. id, extensionTag := calcId(cg, md, pid)
  460. //klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  461. if id == "" {
  462. if cg.Id == "/init.scope" && pid != 1 {
  463. klog.Infoln("ignoring without persisting", "cg", cg.Id, "pid", pid)
  464. } else {
  465. klog.Infoln("ignoring", "cg", cg.Id, "pid", pid)
  466. r.containersByPid[pid] = nil
  467. }
  468. return nil
  469. }
  470. if c := r.containersById[id]; c != nil {
  471. //klog.Warningln("id conflict:", id)
  472. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  473. c.cgroup = cg
  474. c.metadata = md
  475. c.runLogParser("")
  476. if c.nsConntrack != nil {
  477. _ = c.nsConntrack.Close()
  478. c.nsConntrack = nil
  479. }
  480. }
  481. setK8sTag(c, extensionTag, pid)
  482. r.containersByPid[pid] = c
  483. r.containersByCgroupId[cgId] = c
  484. return c
  485. }
  486. c, err := NewContainer(id, cg, md, r.hostConntrack, pid, r)
  487. if err != nil {
  488. klog.Warningf("failed to create container pid=%d cg=%s id=%s: %s", pid, cg.Id, id, err)
  489. return nil
  490. }
  491. //klog.Infoln("detected a new container", "pid", pid, "cg", cg.Id, "id", id)
  492. // add ns/workload/podname/pid/ctype
  493. //sType := fmt.Sprintf("%d", cg.ContainerType)
  494. setK8sTag(c, extensionTag, pid)
  495. if err := prometheus.WrapRegistererWith(setLabels(string(id),
  496. extensionTag[Namespace],
  497. extensionTag[Workload],
  498. extensionTag[PodName],
  499. extensionTag[ProcessName],
  500. fmt.Sprintf("%d", pid)), r.reg).Register(c); err != nil {
  501. klog.Warningln("failed to register container:", err)
  502. return nil
  503. }
  504. r.containersByPid[pid] = c
  505. r.containersByCgroupId[cgId] = c
  506. r.containersById[id] = c
  507. return c
  508. }
  509. func (r *Registry) updateTrafficStatsIfNecessary() {
  510. r.trafficStatsLock.Lock()
  511. defer r.trafficStatsLock.Unlock()
  512. if time.Now().Sub(r.trafficStatsLastUpdated) < MinTrafficStatsUpdateInterval {
  513. return
  514. }
  515. iter := r.tracer.ActiveConnectionsIterator()
  516. cid := ConnectionId{}
  517. stats := Connection{}
  518. for iter.Next(&cid, &stats) {
  519. r.trafficStatsUpdateCh <- &TrafficStatsUpdate{
  520. Pid: cid.PID,
  521. FD: cid.FD,
  522. BytesSent: stats.BytesSent,
  523. BytesReceived: stats.BytesReceived,
  524. }
  525. }
  526. if err := iter.Err(); err != nil {
  527. klog.Warningln(err)
  528. }
  529. r.trafficStatsUpdateCh <- nil
  530. r.trafficStatsLastUpdated = time.Now()
  531. }
  532. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata, pid uint32) (ContainerID, map[string]string) {
  533. // 卡一下防止概率性获取为bash
  534. time.Sleep(1 * time.Millisecond)
  535. procName := proc.GetProcName(pid)
  536. extensionTag := map[string]string{Namespace: "", Workload: "", PodName: "", ProcessName: procName}
  537. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  538. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  539. return "", extensionTag
  540. }
  541. return ContainerID(cg.ContainerId), extensionTag
  542. }
  543. if cg.ContainerType == cgroup.ContainerTypeStandaloneProcess {
  544. //extensionTag[ProcessName] = procName
  545. return ContainerID(fmt.Sprintf("/%s/%s/%d", "standalone", procName, pid)), extensionTag
  546. }
  547. switch cg.ContainerType {
  548. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  549. default:
  550. return "", extensionTag
  551. }
  552. if cg.ContainerId == "" {
  553. return "", extensionTag
  554. }
  555. if md.labels["io.kubernetes.pod.name"] != "" {
  556. pod := md.labels["io.kubernetes.pod.name"]
  557. namespace := md.labels["io.kubernetes.pod.namespace"]
  558. name := md.labels["io.kubernetes.container.name"]
  559. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  560. name = "sandbox"
  561. }
  562. if name == "" || name == "POD" { // skip pause containers
  563. return "", extensionTag
  564. }
  565. extensionTag[Namespace] = namespace
  566. if *flags.RunInContainer {
  567. extensionTag[Workload], _ = kube.GetWorkload(namespace, pod)
  568. }
  569. extensionTag[PodName] = pod
  570. //extensionTag[ProcessName] = name
  571. if g := cronjobPodName.FindStringSubmatch(pod); len(g) == 3 {
  572. now := time.Now()
  573. tsMiniutes, _ := strconv.ParseUint(g[2], 10, 64)
  574. scheduledAt := time.Unix(int64(tsMiniutes)*60, 0)
  575. if scheduledAt.After(now.Add(-cronjobPodScheduleWindow)) && scheduledAt.Before(now.Add(cronjobPodScheduleWindow)) {
  576. return ContainerID(fmt.Sprintf("/k8s-cronjob/%s/%s/%s", namespace, g[1], name)), extensionTag
  577. }
  578. }
  579. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name)), extensionTag
  580. }
  581. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  582. namespace := md.labels["com.docker.stack.namespace"]
  583. service := md.labels["com.docker.swarm.service.name"]
  584. if namespace != "" {
  585. service = strings.TrimPrefix(service, namespace+"_")
  586. }
  587. if namespace == "" {
  588. namespace = "_"
  589. }
  590. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1])), extensionTag
  591. }
  592. if md.env != nil {
  593. allocId := md.env["NOMAD_ALLOC_ID"]
  594. group := md.env["NOMAD_GROUP_NAME"]
  595. job := md.env["NOMAD_JOB_NAME"]
  596. namespace := md.env["NOMAD_NAMESPACE"]
  597. task := md.env["NOMAD_TASK_NAME"]
  598. if allocId != "" && group != "" && job != "" && namespace != "" && task != "" {
  599. return ContainerID(fmt.Sprintf("/nomad/%s/%s/%s/%s/%s", namespace, job, group, allocId, task)), extensionTag
  600. }
  601. }
  602. if md.name == "" { // should be "pure" dockerd container here
  603. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  604. return "", extensionTag
  605. }
  606. return ContainerID("/docker/" + md.name), extensionTag
  607. }
  608. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  609. switch cg.ContainerType {
  610. case cgroup.ContainerTypeSystemdService:
  611. md := &ContainerMetadata{}
  612. md.systemdTriggeredBy = SystemdTriggeredBy(cg.ContainerId)
  613. return md, nil
  614. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  615. default:
  616. return &ContainerMetadata{}, nil
  617. }
  618. if cg.ContainerId == "" {
  619. return &ContainerMetadata{}, nil
  620. }
  621. if cg.ContainerType == cgroup.ContainerTypeCrio {
  622. return CrioInspect(cg.ContainerId)
  623. }
  624. var dockerdErr error
  625. if dockerdClient != nil {
  626. md, err := DockerdInspect(cg.ContainerId)
  627. if err == nil {
  628. return md, nil
  629. }
  630. dockerdErr = err
  631. }
  632. var containerdErr error
  633. if containerdClient != nil {
  634. md, err := ContainerdInspect(cg.ContainerId)
  635. if err == nil {
  636. return md, nil
  637. }
  638. containerdErr = err
  639. }
  640. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  641. }
  642. type TrafficStatsUpdate struct {
  643. Pid uint32
  644. FD uint64
  645. BytesSent uint64
  646. BytesReceived uint64
  647. }