registry.go 24 KB

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