registry.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  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. err := c.RegisterAppInfo(r, e.Pid)
  319. if err != nil {
  320. klog.WithError(err).Errorf("[registry] Failed registerAppInfo. pid is %d", e.Pid)
  321. continue
  322. }
  323. err = c.AttachUprobes(r.tracer, e.Pid)
  324. if err != nil {
  325. klog.WithField("pid", e.Pid).WithError(err).Errorf("[AttachUprobes] [end] Failed attach stack trace!")
  326. }
  327. if !r.tracer.DisableStackTracing() {
  328. err = c.AttachStack(r.tracer, e.Pid)
  329. if err != nil {
  330. klog.WithField("pid", e.Pid).WithError(err).Errorf("[registry] [end] Failed attach stack trace!")
  331. }
  332. }
  333. }
  334. } else {
  335. klog.Infoln("TCP listen open from unknown container", e)
  336. }
  337. case ebpftracer.EventTypeAcceptOpen:
  338. //klog.Infoln("ebpftracer.EventTypeAcceptOpen==================", e.Pid)
  339. if c := r.getOrCreateContainer(e.Pid); c != nil {
  340. c.onAcceptOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false, e.Duration)
  341. c.eventReady()
  342. } else {
  343. klog.Infoln("TCP connection from unknown container", e)
  344. }
  345. case ebpftracer.EventTypeConnectionOpen:
  346. //fmt.Println("ebpftracer.EventTypeConnectionOpen==================", e.Pid)
  347. if c := r.getOrCreateContainer(e.Pid); c != nil {
  348. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, e.Timestamp, false, e.Duration)
  349. if !common.IsOpenFilter() || common.IsFilterPid(e.Pid) {
  350. if !c.checkEventReady() && c.buildIDs(e.Pid) {
  351. c.eventReady()
  352. }
  353. }
  354. if common.IsOpenFilter() && common.IsFilterPid(e.Pid) {
  355. c.WhiteSettingInfo.AppName = enums.TestApp
  356. err := c.RegisterAppInfo(r, e.Pid)
  357. if err != nil {
  358. klog.WithError(err).Errorf("[registry] Failed registerAppInfo. pid is %d", e.Pid)
  359. continue
  360. }
  361. err = c.AttachUprobes(r.tracer, e.Pid)
  362. if err != nil {
  363. klog.WithField("pid", e.Pid).WithError(err).Errorf("[AttachUprobes] [end] Failed attach stack trace!")
  364. }
  365. // 禁用stack
  366. if !r.tracer.DisableStackTracing() {
  367. err = c.AttachStack(r.tracer, e.Pid)
  368. if err != nil {
  369. klog.WithField("pid", e.Pid).WithError(err).Errorf("[registry] [end] Failed attach stack trace!")
  370. }
  371. } else {
  372. klog.Warnf("StackTrace tracing is disabled")
  373. }
  374. }
  375. } else {
  376. klog.Infoln("TCP connection from unknown container", e)
  377. }
  378. case ebpftracer.EventTypeListenClose:
  379. if c := r.containersByPid[e.Pid]; c != nil {
  380. c.onListenClose(e.Pid, e.SrcAddr)
  381. }
  382. case ebpftracer.EventTypeConnectionError:
  383. if c := r.getOrCreateContainer(e.Pid); c != nil {
  384. c.onConnectionOpen(e.Pid, e.Fd, e.SrcAddr, e.DstAddr, 0, true, e.Duration)
  385. } else {
  386. klog.Infoln("TCP connection error from unknown container", e)
  387. }
  388. case ebpftracer.EventTypeConnectionClose:
  389. if c := r.containersByPid[e.Pid]; c != nil {
  390. c.onConnectionClose(e)
  391. }
  392. case ebpftracer.EventTypeAcceptClose:
  393. if c := r.containersByPid[e.Pid]; c != nil {
  394. c.onAcceptClose(e)
  395. }
  396. case ebpftracer.EventTypeTCPRetransmit:
  397. srcDst := AddrPair{src: e.SrcAddr, dst: e.DstAddr}
  398. for _, c := range r.containersById {
  399. if c.onRetransmission(srcDst) {
  400. break
  401. }
  402. }
  403. case ebpftracer.EventTypeL7Request:
  404. //fmt.Println("e.L7Request Payload:", string(e.L7Request.Payload))
  405. if e.L7Request == nil {
  406. continue
  407. }
  408. if c := r.containersByPid[e.Pid]; c != nil {
  409. //fmt.Println("EventTypeL7Request", e.Pid, c.Isl7AttachSuccess())
  410. //a, _ := json.Marshal(e.L7Request)
  411. //fmt.Println("EventTypeL7Request", e.Pid, string(a))
  412. klog.Debugln("Payload:", string(e.L7Request.Payload))
  413. ip2fqdn := c.onL7RequestApm(e.Pid, e.Fd, e.Timestamp, e.L7Request)
  414. r.ip2fqdnLock.Lock()
  415. for ip, fqdn := range ip2fqdn {
  416. r.ip2fqdn[ip] = fqdn
  417. }
  418. r.ip2fqdnLock.Unlock()
  419. }
  420. case ebpftracer.EventTypeOffCpuTIme:
  421. //fmt.Println("e.L7Request Payload:", string(e.L7Request.Payload))
  422. if e.OffCPU == nil {
  423. continue
  424. }
  425. if c := r.getOrCreateContainer(e.Pid); c != nil {
  426. c.onOffCPUTime(e.OffCPU)
  427. } else {
  428. klog.Infoln("EventTypeOffCpuTIme from unknown container", e)
  429. }
  430. case ebpftracer.EventTypeFunEnt:
  431. if e.StackEvent == nil {
  432. continue
  433. }
  434. if c := r.containersByPid[uint32(e.StackEvent.Pid)]; c != nil {
  435. /*if e.StackEvent.Type == uint64(CodeTypeJava) {
  436. 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)
  437. klog.Debugf("e.EventTypeFunEnt: TraceId: MethedName: %d -- %s -- %s", e.StackEvent.Type, e.StackEvent.MethedName, e.StackEvent.ClassName)
  438. } else {
  439. 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)
  440. }*/
  441. c.StackProcess2(*e.StackEvent, r.tracer)
  442. } else {
  443. // 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)
  444. // fmt.Printf("e.EventTypeFunEnt ErrorError: TraceId:%x, FPid:%x, Nid:%x, Level:%d\n", e.StackEvent.Fpid, e.StackEvent.Nid, e.StackEvent.Level)
  445. }
  446. }
  447. }
  448. }
  449. }
  450. func (r *Registry) getOrCreateContainer(pid uint32) *Container {
  451. if c, seen := r.containersByPid[pid]; c != nil {
  452. return c
  453. } else if seen { // ignored
  454. return nil
  455. }
  456. cg, err := proc.ReadCgroup(pid)
  457. if err != nil {
  458. if !common.IsNotExist(err) {
  459. klog.Warningln("failed to read proc cgroup:", err)
  460. }
  461. return nil
  462. }
  463. cgId := fmt.Sprintf("%s/%d", cg.Id, pid)
  464. if c := r.containersByCgroupId[cgId]; c != nil {
  465. r.containersByPid[pid] = c
  466. return c
  467. }
  468. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  469. cmdline := proc.GetCmdline(pid)
  470. parts := bytes.Split(cmdline, []byte{0})
  471. if len(parts) > 0 {
  472. cmd := parts[0]
  473. lastArg := parts[len(parts)-1]
  474. if (bytes.HasSuffix(cmd, []byte("runsc-sandbox")) || bytes.HasSuffix(cmd, []byte("runsc"))) && containerIdRegexp.Match(lastArg) {
  475. cg.ContainerId = string(lastArg)
  476. }
  477. }
  478. }
  479. md, err := getContainerMetadata(cg)
  480. if err != nil {
  481. klog.Warningf("failed to get container metadata for pid %d -> %s: %s", pid, cg.Id, err)
  482. return nil
  483. }
  484. // add ns/workload/podname
  485. id, extensionTag := calcId(cg, md, pid)
  486. //klog.Infof("calculated container id %d -> %s -> %s", pid, cg.Id, id)
  487. if id == "" {
  488. if cg.Id == "/init.scope" && pid != 1 {
  489. klog.Infoln("ignoring without persisting", "cg", cg.Id, "pid", pid)
  490. } else {
  491. klog.Infoln("ignoring", "cg", cg.Id, "pid", pid)
  492. r.containersByPid[pid] = nil
  493. }
  494. return nil
  495. }
  496. if c := r.containersById[id]; c != nil {
  497. //klog.Warningln("id conflict:", id)
  498. if cg.CreatedAt().After(c.cgroup.CreatedAt()) {
  499. c.cgroup = cg
  500. c.metadata = md
  501. c.runLogParser("")
  502. if c.nsConntrack != nil {
  503. _ = c.nsConntrack.Close()
  504. c.nsConntrack = nil
  505. }
  506. }
  507. setK8sTag(c, extensionTag, pid)
  508. r.containersByPid[pid] = c
  509. r.containersByCgroupId[cgId] = c
  510. return c
  511. }
  512. c, err := NewContainer(id, cg, md, r.hostConntrack, pid, r)
  513. if err != nil {
  514. klog.Warningf("failed to create container pid=%d cg=%s id=%s: %s", pid, cg.Id, id, err)
  515. return nil
  516. }
  517. //klog.Infoln("detected a new container", "pid", pid, "cg", cg.Id, "id", id)
  518. // add ns/workload/podname/pid/ctype
  519. //sType := fmt.Sprintf("%d", cg.ContainerType)
  520. setK8sTag(c, extensionTag, pid)
  521. if err := prometheus.WrapRegistererWith(setLabels(string(id),
  522. extensionTag[Namespace],
  523. extensionTag[Workload],
  524. extensionTag[PodName],
  525. extensionTag[ProcessName],
  526. fmt.Sprintf("%d", pid)), r.reg).Register(c); err != nil {
  527. klog.Warningln("failed to register container:", err)
  528. return nil
  529. }
  530. r.containersByPid[pid] = c
  531. r.containersByCgroupId[cgId] = c
  532. r.containersById[id] = c
  533. return c
  534. }
  535. func (r *Registry) updateTrafficStatsIfNecessary() {
  536. r.trafficStatsLock.Lock()
  537. defer r.trafficStatsLock.Unlock()
  538. if time.Now().Sub(r.trafficStatsLastUpdated) < MinTrafficStatsUpdateInterval {
  539. return
  540. }
  541. iter := r.tracer.ActiveConnectionsIterator()
  542. cid := ConnectionId{}
  543. stats := Connection{}
  544. for iter.Next(&cid, &stats) {
  545. r.trafficStatsUpdateCh <- &TrafficStatsUpdate{
  546. Pid: cid.PID,
  547. FD: cid.FD,
  548. BytesSent: stats.BytesSent,
  549. BytesReceived: stats.BytesReceived,
  550. }
  551. }
  552. if err := iter.Err(); err != nil {
  553. klog.Warningln(err)
  554. }
  555. r.trafficStatsUpdateCh <- nil
  556. r.trafficStatsLastUpdated = time.Now()
  557. }
  558. func calcId(cg *cgroup.Cgroup, md *ContainerMetadata, pid uint32) (ContainerID, map[string]string) {
  559. // 卡一下防止概率性获取为bash
  560. time.Sleep(1 * time.Millisecond)
  561. procName := proc.GetProcName(pid)
  562. extensionTag := map[string]string{Namespace: "", Workload: "", PodName: "", ProcessName: procName}
  563. if cg.ContainerType == cgroup.ContainerTypeSystemdService {
  564. if strings.HasPrefix(cg.ContainerId, "/system.slice/crio-conmon-") {
  565. return "", extensionTag
  566. }
  567. return ContainerID(cg.ContainerId), extensionTag
  568. }
  569. if cg.ContainerType == cgroup.ContainerTypeStandaloneProcess {
  570. //extensionTag[ProcessName] = procName
  571. return ContainerID(fmt.Sprintf("/%s/%s/%d", "standalone", procName, pid)), extensionTag
  572. }
  573. switch cg.ContainerType {
  574. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  575. default:
  576. return "", extensionTag
  577. }
  578. if cg.ContainerId == "" {
  579. return "", extensionTag
  580. }
  581. if md.labels["io.kubernetes.pod.name"] != "" {
  582. pod := md.labels["io.kubernetes.pod.name"]
  583. namespace := md.labels["io.kubernetes.pod.namespace"]
  584. name := md.labels["io.kubernetes.container.name"]
  585. if cg.ContainerType == cgroup.ContainerTypeSandbox {
  586. name = "sandbox"
  587. }
  588. if name == "" || name == "POD" { // skip pause containers
  589. return "", extensionTag
  590. }
  591. extensionTag[Namespace] = namespace
  592. if *flags.RunInContainer {
  593. extensionTag[Workload], _ = kube.GetWorkload(namespace, pod)
  594. }
  595. extensionTag[PodName] = pod
  596. //extensionTag[ProcessName] = name
  597. if g := cronjobPodName.FindStringSubmatch(pod); len(g) == 3 {
  598. now := time.Now()
  599. tsMiniutes, _ := strconv.ParseUint(g[2], 10, 64)
  600. scheduledAt := time.Unix(int64(tsMiniutes)*60, 0)
  601. if scheduledAt.After(now.Add(-cronjobPodScheduleWindow)) && scheduledAt.Before(now.Add(cronjobPodScheduleWindow)) {
  602. return ContainerID(fmt.Sprintf("/k8s-cronjob/%s/%s/%s", namespace, g[1], name)), extensionTag
  603. }
  604. }
  605. return ContainerID(fmt.Sprintf("/k8s/%s/%s/%s", namespace, pod, name)), extensionTag
  606. }
  607. if taskNameParts := strings.SplitN(md.labels["com.docker.swarm.task.name"], ".", 3); len(taskNameParts) == 3 {
  608. namespace := md.labels["com.docker.stack.namespace"]
  609. service := md.labels["com.docker.swarm.service.name"]
  610. if namespace != "" {
  611. service = strings.TrimPrefix(service, namespace+"_")
  612. }
  613. if namespace == "" {
  614. namespace = "_"
  615. }
  616. return ContainerID(fmt.Sprintf("/swarm/%s/%s/%s", namespace, service, taskNameParts[1])), extensionTag
  617. }
  618. if md.env != nil {
  619. allocId := md.env["NOMAD_ALLOC_ID"]
  620. group := md.env["NOMAD_GROUP_NAME"]
  621. job := md.env["NOMAD_JOB_NAME"]
  622. namespace := md.env["NOMAD_NAMESPACE"]
  623. task := md.env["NOMAD_TASK_NAME"]
  624. if allocId != "" && group != "" && job != "" && namespace != "" && task != "" {
  625. return ContainerID(fmt.Sprintf("/nomad/%s/%s/%s/%s/%s", namespace, job, group, allocId, task)), extensionTag
  626. }
  627. }
  628. if md.name == "" { // should be "pure" dockerd container here
  629. klog.Warningln("empty dockerd container name for:", cg.ContainerId)
  630. return "", extensionTag
  631. }
  632. return ContainerID("/docker/" + md.name), extensionTag
  633. }
  634. func getContainerMetadata(cg *cgroup.Cgroup) (*ContainerMetadata, error) {
  635. switch cg.ContainerType {
  636. case cgroup.ContainerTypeSystemdService:
  637. md := &ContainerMetadata{}
  638. md.systemdTriggeredBy = SystemdTriggeredBy(cg.ContainerId)
  639. return md, nil
  640. case cgroup.ContainerTypeDocker, cgroup.ContainerTypeContainerd, cgroup.ContainerTypeSandbox, cgroup.ContainerTypeCrio:
  641. default:
  642. return &ContainerMetadata{}, nil
  643. }
  644. if cg.ContainerId == "" {
  645. return &ContainerMetadata{}, nil
  646. }
  647. if cg.ContainerType == cgroup.ContainerTypeCrio {
  648. return CrioInspect(cg.ContainerId)
  649. }
  650. var dockerdErr error
  651. if dockerdClient != nil {
  652. md, err := DockerdInspect(cg.ContainerId)
  653. if err == nil {
  654. return md, nil
  655. }
  656. dockerdErr = err
  657. }
  658. var containerdErr error
  659. if containerdClient != nil {
  660. md, err := ContainerdInspect(cg.ContainerId)
  661. if err == nil {
  662. return md, nil
  663. }
  664. containerdErr = err
  665. }
  666. return nil, fmt.Errorf("failed to interact with dockerd (%s) or with containerd (%s)", dockerdErr, containerdErr)
  667. }
  668. type TrafficStatsUpdate struct {
  669. Pid uint32
  670. FD uint64
  671. BytesSent uint64
  672. BytesReceived uint64
  673. }
  674. func (r *Registry) IsFusing() bool {
  675. return r.isFusing
  676. }