registry.go 24 KB

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