container_apm.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. package containers
  2. import (
  3. "bufio"
  4. "bytes"
  5. "debug/elf"
  6. "fmt"
  7. "github.com/cilium/ebpf/link"
  8. "github.com/coroot/coroot-node-agent/flags"
  9. "os"
  10. "path"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/coroot/coroot-node-agent/ebpftracer"
  16. "github.com/coroot/coroot-node-agent/ebpftracer/l7"
  17. "github.com/coroot/coroot-node-agent/ebpftracer/tracer"
  18. "github.com/coroot/coroot-node-agent/proc"
  19. "github.com/coroot/coroot-node-agent/tracing"
  20. "github.com/coroot/coroot-node-agent/utils"
  21. . "github.com/coroot/coroot-node-agent/utils/modelse"
  22. "github.com/pkg/errors"
  23. klog "github.com/sirupsen/logrus"
  24. "inet.af/netaddr"
  25. )
  26. const (
  27. TRACE_STATUS = 1
  28. )
  29. func (c *Container) getTrace(traceId uint64) (*tracing.Trace, bool) {
  30. trace, ok := c.traceMap[traceId]
  31. return trace, ok
  32. }
  33. func (c *Container) createTraceMap(traceId uint64, trace *tracing.Trace) {
  34. c.traceMap[traceId] = trace
  35. }
  36. // 查询或创建trace信息
  37. func (c *Container) getOrInitTrace(traceId uint64) (*tracing.Trace, error) {
  38. trace, ok := c.getTrace(traceId)
  39. if !ok {
  40. //new trace
  41. trace = tracing.NewTraceFromEvent(string(c.id))
  42. //create TraceMap
  43. c.createTraceMap(traceId, trace)
  44. //create ParentSpan
  45. trace.CreateRootSpan(traceId)
  46. }
  47. return trace, nil
  48. }
  49. func (c *Container) InitTrace(traceId uint64, r *l7.RequestData) error {
  50. method, path, hostIp, port := l7.ParseHttpHost(r.Payload)
  51. ip, err := netaddr.ParseIP(hostIp)
  52. if err != nil {
  53. fmt.Println("host ip error")
  54. hostIp = "127.0.0.1"
  55. }
  56. addr := netaddr.IPPortFrom(ip, port)
  57. trace := tracing.NewTrace(string(c.id), addr)
  58. if trace == nil {
  59. return fmt.Errorf("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT is null")
  60. }
  61. c.traceMap[traceId] = trace
  62. trace.TraceStart(method, path, r.Status, r.Duration)
  63. return nil
  64. }
  65. // 在任意阶段,r.TraceId 不等于0 则创建 traceMap && createParentSpan
  66. // 更新 createTraceSpan 机制,更新触发traceEnd机制,当事件个数满足时,任意event均可触发end
  67. func (c *Container) SendEvent(t *tracing.Trace, traceID uint64) {
  68. if t.AllEventReady(traceID) {
  69. t.SendEvent()
  70. klog.Infof("SendEvent %d", traceID)
  71. //fmt.Println(t.GetSpan())
  72. //fmt.Println("===============")
  73. delete(c.traceMap, traceID)
  74. }
  75. }
  76. func (c *Container) valuableTrace(traceID uint64) bool {
  77. return traceID != 0
  78. }
  79. func (c *Container) onL7RequestApm(pid uint32, fd uint64, timestamp uint64, r *l7.RequestData) map[netaddr.IP]string {
  80. c.lock.Lock()
  81. defer c.lock.Unlock()
  82. if r.Protocol == l7.ProtocolDNS {
  83. ip2fqdn, _type, fqdn := c.onDNSRequest(r)
  84. if c.l7Attach && c.valuableTrace(r.TraceId) {
  85. apmTrace, err := c.getOrInitTrace(r.TraceId)
  86. if err == nil {
  87. apmTrace.DNSTraceQueryEvent(r, _type, fqdn)
  88. c.SendEvent(apmTrace, r.TraceId)
  89. }
  90. }
  91. return ip2fqdn
  92. }
  93. //if !c.valuableTrace(r.TraceId) {
  94. // return nil
  95. //}
  96. // klog.Infof("====ProtocolTrace+++++ start==== %d %d", pid, r.TraceId)
  97. // klog.Infof("====ProtocolTrace===== start==== %d %d", r.Protocol == l7.ProtocolTrace, c.l7Attach)
  98. if r.Protocol == l7.ProtocolTrace && c.l7Attach && c.valuableTrace(r.TraceId) {
  99. // klog.Infof("====ProtocolTrace---- start==== %d %d", pid, r.TraceId)
  100. if r.TraceStart == TRACE_STATUS {
  101. // klog.Infof("====ProtocolTrace start==== %d %d", pid, r.TraceId)
  102. trace, err := c.getOrInitTrace(r.TraceId)
  103. klog.Infof("payload:[%s]", r.Payload)
  104. if err == nil {
  105. method, requestURI, sn, sport := l7.ParseHttpHost(r.Payload)
  106. ip, _ := netaddr.ParseIP(sn)
  107. //codeType := c.GetCodeTypeFromCache(pid)
  108. trace.TraceStartEvent(method, requestURI, sn, sport, r.Status, netaddr.IPPortFrom(ip, sport), pid, c.GetAppInfo())
  109. c.SendEvent(trace, r.TraceId)
  110. }
  111. return nil
  112. }
  113. if r.TraceEnd == TRACE_STATUS {
  114. klog.Infof("====ProtocolTrace end==== %d %d", pid, r.TraceId)
  115. trace, err := c.getOrInitTrace(r.TraceId)
  116. if err == nil {
  117. trace.TraceEndEvent(r)
  118. c.SendEvent(trace, r.TraceId)
  119. }
  120. return nil
  121. }
  122. }
  123. if r.Protocol == l7.ProtocolHTTP {
  124. if c.l7Attach && c.valuableTrace(r.TraceId) {
  125. method, requestURI, sn, sport := l7.ParseHttpHost(r.Payload)
  126. apmTrace, err := c.getOrInitTrace(r.TraceId)
  127. //fmt.Println("ProtocolHTTP-----", r.TraceId, err)
  128. if err == nil {
  129. apmTrace.HttpTraceRequestEvent(method, requestURI, sn, sport, r)
  130. c.SendEvent(apmTrace, r.TraceId)
  131. }
  132. }
  133. //return nil
  134. }
  135. conn := c.connectionsByPidFd[PidFd{Pid: pid, Fd: fd}]
  136. //fmt.Println("l7.connectionsByPidFd", conn, pid, fd)
  137. if conn == nil {
  138. return nil
  139. }
  140. if timestamp != 0 && conn.Timestamp != timestamp {
  141. return nil
  142. }
  143. stats := c.l7Stats.get(r.Protocol, conn.Dest, conn.ActualDest)
  144. //trace := tracing.NewTrace(string(c.id), conn.ActualDest)
  145. switch r.Protocol {
  146. case l7.ProtocolHTTP:
  147. stats.observe(r.Status.Http(), "", r.Duration)
  148. case l7.ProtocolHTTP2:
  149. if conn.http2Parser == nil {
  150. conn.http2Parser = l7.NewHttp2Parser()
  151. }
  152. requests := conn.http2Parser.Parse(r.Method, r.Payload, uint64(r.Duration))
  153. for _, req := range requests {
  154. stats.observe(req.Status.Http(), "", req.Duration)
  155. //trace.Http2Request(req.Method, req.Path, req.Scheme, req.Status, req.Duration)
  156. }
  157. case l7.ProtocolPostgres:
  158. if r.Method != l7.MethodStatementClose {
  159. stats.observe(r.Status.String(), "", r.Duration)
  160. }
  161. //if conn.postgresParser == nil {
  162. // conn.postgresParser = l7.NewPostgresParser()
  163. //}
  164. //query := conn.postgresParser.Parse(r.Payload)
  165. //trace.PostgresQuery(query, r.Status.Error(), r.Duration)
  166. case l7.ProtocolMysql:
  167. if r.Method != l7.MethodStatementClose {
  168. stats.observe(r.Status.String(), "", r.Duration)
  169. }
  170. if c.l7Attach && c.valuableTrace(r.TraceId) {
  171. if conn.mysqlParser == nil {
  172. conn.mysqlParser = l7.NewMysqlParser()
  173. }
  174. query := conn.mysqlParser.Parse(r.Payload, r.StatementId)
  175. //trace.MysqlQuery(query, r.Status.Error(), r.Duration)
  176. //apmTrace, ok := c.getTrace(r.TraceId)
  177. apmTrace, err := c.getOrInitTrace(r.TraceId)
  178. fmt.Println(err)
  179. //fmt.Println("mysql r.TraceId:", r.TraceId)
  180. //fmt.Println("ok:", ok)
  181. //fmt.Println("traceMap:", len(c.traceMap))
  182. if err == nil {
  183. //apmTrace.MysqlTraceQuery(query, r.Status.Error(), r.Duration, conn.ActualDest)
  184. apmTrace.MysqlTraceQueryEvent(query, r, conn.ActualDest)
  185. c.SendEvent(apmTrace, r.TraceId)
  186. }
  187. }
  188. case l7.ProtocolDM:
  189. //统计dm的query次数
  190. stats.observe(r.Status.String(), "", r.Duration)
  191. //是否发送数据
  192. if c.l7Attach && c.valuableTrace(r.TraceId) {
  193. if conn.dmParser == nil {
  194. conn.dmParser = l7.NewDmParser()
  195. }
  196. query := conn.dmParser.Parse(r.Payload, r.StatementId)
  197. apmTrace, err := c.getOrInitTrace(r.TraceId)
  198. if err == nil {
  199. apmTrace.DmTraceQueryEvent(query, r, conn.ActualDest)
  200. c.SendEvent(apmTrace, r.TraceId)
  201. }
  202. }
  203. case l7.ProtocolMemcached:
  204. stats.observe(r.Status.String(), "", r.Duration)
  205. if c.l7Attach && c.valuableTrace(r.TraceId) {
  206. }
  207. //cmd, items := l7.ParseMemcached(r.Payload)
  208. //trace.MemcachedQuery(cmd, items, r.Status.Error(), r.Duration)
  209. case l7.ProtocolRedis:
  210. stats.observe(r.Status.String(), "", r.Duration)
  211. if c.l7Attach && c.valuableTrace(r.TraceId) {
  212. cmd, args := l7.ParseRedis(r.Payload)
  213. //fmt.Println("cmd", cmd)
  214. //fmt.Println("args", args)
  215. //apmTrace, ok := c.getTrace(r.TraceId)
  216. apmTrace, err := c.getOrInitTrace(r.TraceId)
  217. if err == nil {
  218. //apmTrace.RedisTraceQuery(cmd, args, r.Status.Error(), r.Duration)
  219. apmTrace.RedisTraceQueryEvent(cmd, args, r, conn.ActualDest)
  220. c.SendEvent(apmTrace, r.TraceId)
  221. }
  222. }
  223. //trace.RedisQuery(cmd, args, r.Status.Error(), r.Duration)
  224. case l7.ProtocolMongo:
  225. stats.observe(r.Status.String(), "", r.Duration)
  226. if c.l7Attach && c.valuableTrace(r.TraceId) {
  227. }
  228. //query := l7.ParseMongo(r.Payload)
  229. //trace.MongoQuery(query, r.Status.Error(), r.Duration)
  230. case l7.ProtocolKafka, l7.ProtocolCassandra:
  231. stats.observe(r.Status.String(), "", r.Duration)
  232. if c.l7Attach && c.valuableTrace(r.TraceId) {
  233. }
  234. case l7.ProtocolRabbitmq, l7.ProtocolNats:
  235. stats.observe(r.Status.String(), r.Method.String(), 0)
  236. if c.l7Attach && c.valuableTrace(r.TraceId) {
  237. }
  238. case l7.ProtocolDubbo2:
  239. stats.observe(r.Status.String(), "", r.Duration)
  240. if c.l7Attach && c.valuableTrace(r.TraceId) {
  241. }
  242. }
  243. return nil
  244. }
  245. func (c *Container) buildIDs(pid uint32) bool {
  246. c.lock.Lock()
  247. defer c.lock.Unlock()
  248. p := c.processes[pid]
  249. if p != nil {
  250. p.cmdline = string(proc.GetRealCmdline(pid))
  251. }
  252. for address, val := range c.getListens() {
  253. if val == 1 {
  254. ip := address.IP()
  255. if ip.Is4() && !ip.IsLoopback() {
  256. // 获取端口号
  257. port := address.Port()
  258. //c.instanceID.IntVal, c.instanceID.HashtVal, _ =
  259. c.AppInfo.Sn = ip.String()
  260. c.AppInfo.Sport = int(port)
  261. strInstanceID := utils.BuildInt64ID(fmt.Sprintf("%s:%d", ip.String(), port))
  262. c.AppInfo.InstanceIdHash.IntVal, _ = strInstanceID.ToInt64()
  263. c.AppInfo.InstanceIdHash.HashtVal = strInstanceID.ToHashByte()
  264. //c.AppInfo.InstanceId = c.instanceID.IntVal
  265. strAgentID := utils.BuildInt64ID(fmt.Sprintf("%s:%s", strInstanceID, string(proc.GetExe(pid))))
  266. c.AppInfo.AgentId, _ = strAgentID.ToInt64()
  267. c.AppInfo.CodeType = c.GetCodeTypeFromCache(pid)
  268. return true
  269. }
  270. }
  271. }
  272. return false
  273. }
  274. func (c *Container) StackProcess(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  275. c.lock.Lock()
  276. defer c.lock.Unlock()
  277. // get the associated uprobe
  278. uprobe, err := c.GetUprobe(event, tracer)
  279. if err != nil {
  280. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  281. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  282. return
  283. }
  284. if event.TraceId <= 0 {
  285. fmt.Println("StackProcess TraceId id 0")
  286. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  287. return
  288. }
  289. // fmt.Printf("StackProcess 函数入口开始处理 fun:TraceId:%lld, Funcname:%s, time: %lld\n", event.TraceId, uprobe.Funcname, event.TimeNsEnd-event.TimeNsStart)
  290. stackFun := ebpftracer.StackFunEvent{}
  291. stackFun.Uprobe = &uprobe
  292. stackFun.StackEvent = event
  293. apmTrace, ok := c.getTrace(event.TraceId)
  294. if ok {
  295. apmTrace.FunAdd(stackFun)
  296. }
  297. }
  298. func byteExtractString(nameString [100]byte) string {
  299. n := bytes.IndexByte(nameString[:], 0)
  300. if n == -1 {
  301. n = len(nameString) // 没找到零值,使用数组长度
  302. }
  303. return string(nameString[:n])
  304. }
  305. func (c *Container) StackProcess2(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  306. c.lock.Lock()
  307. defer c.lock.Unlock()
  308. // get the associated uprobe
  309. switch event.Location {
  310. case 0: // ret
  311. Funcname := ""
  312. if event.Type != uint64(CodeTypeJava) {
  313. uprobe, err := c.GetUprobe(event, tracer)
  314. if err != nil {
  315. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  316. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  317. return
  318. }
  319. Funcname = uprobe.Funcname
  320. } else {
  321. ClassName := byteExtractString(event.ClassName)
  322. MethedName := byteExtractString(event.MethedName)
  323. Funcname = ClassName + "." + MethedName
  324. }
  325. if event.TraceId <= 0 {
  326. fmt.Println("StackProcess TraceId id 0")
  327. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  328. return
  329. }
  330. //fmt.Printf("StackProcess 函数入口开始处理 fun:TraceId:%lld, Funcname:%s, time: %lld\n", event.TraceId, uprobe.Funcname, event.TimeNsEnd-event.TimeNsStart)
  331. apmTrace, err := c.getOrInitTrace(event.TraceId)
  332. if err == nil {
  333. //fmt.Println("append FuncTraceQuery fun:", event.TraceId, uprobe.Funcname, event.Pid)
  334. duration := event.TimeNsEnd - event.TimeNsStart
  335. apmTrace.FuncTraceQuery(Funcname, time.Duration(duration), event.TimeNsStart, event.TimeNsEnd)
  336. c.SendEvent(apmTrace, event.TraceId)
  337. }
  338. }
  339. }
  340. // ResolveAddress returns the symbol(s) and offset of the given address.
  341. func (c *Container) ResolveAddress(addr uint64, symbols []elf.Symbol) (syms []elf.Symbol, offset uint, err error) {
  342. if addr == 0 {
  343. // err = errors.Wrapf(SymbolNotFoundError, "0")
  344. return
  345. }
  346. // symbols, _, err := e.Symbols()
  347. if err != nil {
  348. return
  349. }
  350. idx := sort.Search(len(symbols), func(i int) bool { return symbols[i].Value > addr })
  351. if idx == 0 {
  352. // err = errors.Wrap(SymbolNotFoundError, fmt.Sprintf("%x", addr))
  353. return
  354. }
  355. // why diff symbol may contains the same addr?
  356. sym := symbols[idx-1]
  357. for i := idx - 1; i >= 0 && symbols[i].Value == sym.Value; i-- {
  358. syms = append(syms, symbols[i])
  359. }
  360. for i := idx; i < len(symbols) && symbols[i].Value == sym.Value; i++ {
  361. syms = append(syms, symbols[i])
  362. }
  363. return syms, uint(addr - sym.Value), nil
  364. }
  365. type MemoryMap struct {
  366. Start, End uint64
  367. }
  368. // ReadFirstLineOfMapsFile reads the first line of /proc/<pid>/maps file and return the memory map as a MemoryMap struct
  369. func ReadFirstLineOfMapsFile(pid string) (*MemoryMap, error) {
  370. file, err := os.Open(fmt.Sprintf("/proc/%s/maps", pid))
  371. if err != nil {
  372. return nil, err
  373. }
  374. defer file.Close()
  375. scanner := bufio.NewScanner(file)
  376. if scanner.Scan() {
  377. fields := strings.Fields(scanner.Text())
  378. addresses := strings.Split(fields[0], "-")
  379. if len(addresses) != 2 {
  380. return nil, errors.New("unexpected format in /proc/<pid>/maps")
  381. }
  382. start, err := strconv.ParseUint(addresses[0], 16, 64)
  383. if err != nil {
  384. return nil, err
  385. }
  386. end, err := strconv.ParseUint(addresses[1], 16, 64)
  387. if err != nil {
  388. return nil, err
  389. }
  390. return &MemoryMap{
  391. Start: start,
  392. End: end,
  393. }, nil
  394. }
  395. if err := scanner.Err(); err != nil {
  396. return nil, err
  397. }
  398. return nil, errors.New("empty /proc/<pid>/maps")
  399. }
  400. func (c *Container) GetUprobe(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) (uprobe tracer.Uprobe, err error) {
  401. //fmt.Println("GetUprobe entory:")
  402. memoryMap, _ := ReadFirstLineOfMapsFile(strconv.Itoa(int(event.Pid)))
  403. Address := event.Ip - memoryMap.Start
  404. // fmt.Printf("memoryMap.Start: %x, event.Ip: %x, Address: %x\n", memoryMap.Start, event.Ip, Address)
  405. for _, fun := range c.UprobesMap {
  406. funAddress := fun.Address + fun.AbsOffset
  407. // fmt.Printf("GetUprobeGetUprobeGetUprobe:fun.Address %x, fun.AbsOffset: %x\n", fun.Address, fun.AbsOffset)
  408. if funAddress == Address {
  409. // fmt.Printf("---GetUprobeGetUprobeGetUprobe: %x, event.Ip: %x ---- %s--%x\n", memoryMap.Start, event.Ip, fun.Funcname, fun.Address)
  410. return fun, nil
  411. }
  412. }
  413. syms, _, err := c.ResolveAddress(event.Ip, tracer.Symbols)
  414. if err != nil {
  415. return
  416. }
  417. for _, sym := range syms {
  418. //fmt.Println("GetUprobeGetUprobeGetUprobe: %s+%d", sym.Name, offset)
  419. uprobe, ok := tracer.UprobesMap[fmt.Sprintf("%s-%s", sym.Name, sym.Value)]
  420. if ok {
  421. return uprobe, nil
  422. }
  423. }
  424. err = errors.New("uprobe not found")
  425. return
  426. }
  427. func (c *Container) GetAppInfo() AppInfo {
  428. return c.AppInfo
  429. }
  430. // 可注入前置
  431. func (c *Container) checkEventReady() bool {
  432. c.lock.Lock()
  433. defer c.lock.Unlock()
  434. return c.l7EventReady
  435. }
  436. func (c *Container) eventReady() {
  437. c.lock.Lock()
  438. defer c.lock.Unlock()
  439. c.l7EventReady = true
  440. }
  441. // uprobe前置
  442. func (c *Container) checkL7AttachReady() bool {
  443. c.lock.Lock()
  444. defer c.lock.Unlock()
  445. return c.l7Attach
  446. }
  447. func (c *Container) l7AttachSuccess() {
  448. c.lock.Lock()
  449. defer c.lock.Unlock()
  450. c.l7Attach = true
  451. }
  452. func (c *Container) verifyAttachConditions(r *Registry, pid uint32) (bool, int) {
  453. p := c.processes[pid]
  454. if p != nil && c.checkEventReady() {
  455. codeType := c.GetCodeTypeFromCache(pid)
  456. if codeType.IsUnknownCode() {
  457. klog.WithField("pid", pid).Debug("[verify] unknown language.")
  458. return false, 0
  459. }
  460. cmdline := p.GetCmdline()
  461. if len(cmdline) == 0 {
  462. return false, 0
  463. }
  464. //whiteListByCode := r.getWhiteListByCodeType(codeType)
  465. whiteListByCode := r.getWhiteListAll()
  466. //klog.WithField("pid", pid).WithField("codeType", codeType.String()).
  467. // Infof("[verify] white list %v", utils.ToString(whiteListByCode))
  468. // 当前语言的白名单规则
  469. for _, setting := range whiteListByCode {
  470. ruleVal := setting.Filters
  471. if ruleVal == "" {
  472. continue
  473. }
  474. // 判断规则
  475. if strings.Contains(cmdline, ruleVal) {
  476. c.WhiteSettingInfo = setting
  477. klog.WithField("pid", pid).
  478. WithField("codeType", codeType.String()).
  479. WithField("ruleVal", ruleVal).
  480. WithField("cmdline", cmdline).
  481. WithField("stack", setting.OpenStack).
  482. WithField("white list", utils.ToString(whiteListByCode)).
  483. Infoln("[verify] check successful.")
  484. return true, setting.OpenStack
  485. }
  486. }
  487. }
  488. return false, 0
  489. }
  490. // 1.卸载入口
  491. func (c *Container) Detach(pid uint32, detachType int) {
  492. c.lock.Lock()
  493. defer c.lock.Unlock()
  494. if p := c.processes[pid]; p != nil {
  495. err := c.DetachUprobes(pid, detachType)
  496. if err != nil {
  497. return
  498. }
  499. err = c.DetachStack(pid)
  500. if err != nil {
  501. return
  502. }
  503. // 关闭7层监控
  504. c.l7Attach = false
  505. // 变更应用为卸载状态
  506. c.AppInfo.AppUninstall()
  507. }
  508. }
  509. // 1.1卸载uprobe
  510. func (c *Container) DetachUprobes(pid uint32, detachType int) error {
  511. // close uprobe
  512. if p := c.processes[pid]; p != nil {
  513. for _, u := range p.uprobes {
  514. err := u.Close()
  515. if err != nil {
  516. return err
  517. }
  518. }
  519. p.uprobes = []link.Link{}
  520. switch detachType {
  521. case UNINSTALL_DETACH:
  522. codeType := c.GetCodeTypeFromCache(pid)
  523. switch codeType {
  524. case CodeTypeJava:
  525. p.jvmAttachOnce = false
  526. case CodeTypeGo:
  527. p.goTlsUprobesChecked = false
  528. p.openSslUprobesChecked = false
  529. default:
  530. }
  531. case ERROR_DETACH:
  532. klog.Infof("[DetachUprobes] ERROR_DETACH for pid %d", pid)
  533. default:
  534. }
  535. } else {
  536. return fmt.Errorf("[DetachUprobes] cannot find uprobe for pid %d", pid)
  537. }
  538. return nil
  539. }
  540. // 1.2卸载堆栈
  541. func (c *Container) DetachStack(pid uint32) error {
  542. if p := c.processes[pid]; p != nil {
  543. var err error
  544. codeType := c.GetCodeTypeFromCache(pid)
  545. switch codeType {
  546. case CodeTypeJava:
  547. err = c.detachJvmStack(pid)
  548. default:
  549. err = p.closeStackUprobes()
  550. }
  551. if err != nil {
  552. klog.WithError(err).Errorln("[detachStack] failed to detach stack")
  553. return err
  554. }
  555. p.stackAttachOnce = false
  556. } else {
  557. return fmt.Errorf("[DetachStack] cannot find uprobe for pid %d", pid)
  558. }
  559. return nil
  560. }
  561. // 1.2.1 卸载 jvm堆栈
  562. func (c *Container) detachJvmStack(pid uint32) error {
  563. if p := c.processes[pid]; p != nil {
  564. var err error
  565. if p.stackStatus.IsJattachSuccess() {
  566. // 卸载 JavaAgent
  567. err = p.uninstallJavaAgent()
  568. klog.WithError(err).Errorln("[detachJvmStack] uninstallJavaAgent")
  569. }
  570. if p.stackStatus.IsStackUprobesSuccess() || len(p.stackUprobes) > 0 {
  571. // 卸载堆栈probes
  572. err = p.closeStackUprobes()
  573. klog.WithError(err).Errorln("[detachJvmStack] closeStackUprobes")
  574. }
  575. return err
  576. }
  577. return nil
  578. }
  579. func (c *Container) getRootfs() string {
  580. if c.metadata != nil && c.metadata.rootfs != "" {
  581. return path.Join(*flags.HostDirPathPrefix, c.metadata.rootfs)
  582. }
  583. return ""
  584. }