registry.go 22 KB

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