registry.go 25 KB

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