registry.go 22 KB

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