registry.go 23 KB

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