registry.go 22 KB

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