registry.go 25 KB

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