registry.go 23 KB

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