registry.go 21 KB

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