registry.go 21 KB

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