container_apm.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837
  1. package containers
  2. import (
  3. "bufio"
  4. "bytes"
  5. "debug/elf"
  6. "fmt"
  7. "os"
  8. "path"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/cilium/ebpf/link"
  14. "github.com/coroot/coroot-node-agent/flags"
  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. semconv "go.opentelemetry.io/otel/semconv/v1.18.0"
  25. "inet.af/netaddr"
  26. )
  27. const (
  28. TRACE_STATUS = 1
  29. )
  30. func (c *Container) getTrace(traceId uint64) (*tracing.Trace, bool) {
  31. trace, ok := c.traceMap[traceId]
  32. return trace, ok
  33. }
  34. func (c *Container) createTraceMap(traceId uint64, trace *tracing.Trace) {
  35. c.traceMap[traceId] = trace
  36. }
  37. // 查询或创建trace信息
  38. func (c *Container) getOrInitTrace(traceId uint64) (*tracing.Trace, error) {
  39. trace, ok := c.getTrace(traceId)
  40. if !ok {
  41. //new trace
  42. trace = tracing.NewTraceFromEvent(string(c.id))
  43. //create TraceMap
  44. c.createTraceMap(traceId, trace)
  45. //create ParentSpan
  46. trace.CreateRootSpan(traceId)
  47. }
  48. return trace, nil
  49. }
  50. func (c *Container) InitTrace(traceId uint64, r *l7.RequestData) error {
  51. method, path, hostIp, port := l7.ParseHttpHost(r.Payload)
  52. ip, err := netaddr.ParseIP(hostIp)
  53. if err != nil {
  54. fmt.Println("host ip error")
  55. hostIp = "127.0.0.1"
  56. }
  57. addr := netaddr.IPPortFrom(ip, port)
  58. trace := tracing.NewTrace(string(c.id), addr)
  59. if trace == nil {
  60. return fmt.Errorf("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT is null")
  61. }
  62. c.traceMap[traceId] = trace
  63. trace.TraceStart(method, path, r.Status, r.Duration)
  64. return nil
  65. }
  66. // 在任意阶段,r.TraceId 不等于0 则创建 traceMap && createParentSpan
  67. // 更新 createTraceSpan 机制,更新触发traceEnd机制,当事件个数满足时,任意event均可触发end
  68. func (c *Container) SendEvent(t *tracing.Trace, traceID uint64) {
  69. if t.AllEventReady(traceID) {
  70. t.SendEvent()
  71. klog.Infof("SendEvent %d", traceID)
  72. //fmt.Println(t.GetSpan())
  73. //fmt.Println("===============")
  74. delete(c.traceMap, traceID)
  75. }
  76. }
  77. func (c *Container) valuableTrace(traceID uint64) bool {
  78. return traceID != 0
  79. }
  80. func (c *Container) onL7RequestApm(pid uint32, fd uint64, timestamp uint64, r *l7.RequestData) map[netaddr.IP]string {
  81. c.lock.Lock()
  82. defer c.lock.Unlock()
  83. if r.Protocol == l7.ProtocolDNS {
  84. ip2fqdn, _type, fqdn, ttl, ips := c.onDNSRequest(r)
  85. if c.l7Attach && c.valuableTrace(r.TraceId) {
  86. apmTrace, err := c.getOrInitTrace(r.TraceId)
  87. if err == nil {
  88. apmTrace.DNSTraceQueryEvent(r, _type, fqdn, ttl, ips)
  89. c.SendEvent(apmTrace, r.TraceId)
  90. }
  91. }
  92. return ip2fqdn
  93. }
  94. //if !c.valuableTrace(r.TraceId) {
  95. // return nil
  96. //}
  97. // klog.Infof("====ProtocolTrace+++++ start==== %d %d", pid, r.TraceId)
  98. // klog.Infof("====ProtocolTrace===== start==== %d %d", r.Protocol == l7.ProtocolTrace, c.l7Attach)
  99. if r.Protocol == l7.ProtocolTrace && c.l7Attach && c.valuableTrace(r.TraceId) {
  100. // klog.Infof("====ProtocolTrace---- start==== %d %d", pid, r.TraceId)
  101. if r.TraceStart == TRACE_STATUS {
  102. // klog.Infof("====ProtocolTrace start==== %d %d", pid, r.TraceId)
  103. trace, err := c.getOrInitTrace(r.TraceId)
  104. klog.Infof("payload:[%s]", r.Payload)
  105. if err == nil {
  106. method, requestURI, sn, sport := l7.ParseHttpHost(r.Payload)
  107. ip, _ := netaddr.ParseIP(sn)
  108. //codeType := c.GetCodeTypeFromCache(pid)
  109. trace.TraceStartEvent(method, requestURI, sn, sport, r.Status, netaddr.IPPortFrom(ip, sport), pid, c.GetAppInfo())
  110. c.SendEvent(trace, r.TraceId)
  111. }
  112. return nil
  113. }
  114. if r.TraceEnd == TRACE_STATUS {
  115. klog.Infof("====ProtocolTrace end==== %d %d", pid, r.TraceId)
  116. trace, err := c.getOrInitTrace(r.TraceId)
  117. if err == nil {
  118. trace.TraceEndEvent(r)
  119. c.SendEvent(trace, r.TraceId)
  120. }
  121. return nil
  122. }
  123. }
  124. if r.Protocol == l7.ProtocolHTTP {
  125. if c.l7Attach && c.valuableTrace(r.TraceId) {
  126. method, requestURI, sn, sport := l7.ParseHttpHost(r.Payload)
  127. apmTrace, err := c.getOrInitTrace(r.TraceId)
  128. //fmt.Println("ProtocolHTTP-----", r.TraceId, err)
  129. if err == nil {
  130. apmTrace.HttpTraceRequestEvent(method, requestURI, sn, sport, r)
  131. c.SendEvent(apmTrace, r.TraceId)
  132. }
  133. }
  134. //return nil
  135. }
  136. conn := c.connectionsByPidFd[PidFd{Pid: pid, Fd: fd}]
  137. //fmt.Println("l7.connectionsByPidFd", conn, pid, fd)
  138. if conn == nil {
  139. return nil
  140. }
  141. if timestamp != 0 && conn.Timestamp != timestamp {
  142. return nil
  143. }
  144. stats := c.l7Stats.get(r.Protocol, conn.Dest, conn.ActualDest)
  145. //trace := tracing.NewTrace(string(c.id), conn.ActualDest)
  146. switch r.Protocol {
  147. case l7.ProtocolHTTP:
  148. stats.observe(r.Status.Http(), "", r.Duration)
  149. case l7.ProtocolHTTP2:
  150. if conn.http2Parser == nil {
  151. conn.http2Parser = l7.NewHttp2Parser()
  152. }
  153. requests := conn.http2Parser.Parse(r.Method, r.Payload, uint64(r.Duration))
  154. for _, req := range requests {
  155. stats.observe(req.Status.Http(), "", req.Duration)
  156. //trace.Http2Request(req.Method, req.Path, req.Scheme, req.Status, req.Duration)
  157. }
  158. case l7.ProtocolPostgres:
  159. if r.Method != l7.MethodStatementClose {
  160. stats.observe(r.Status.String(), "", r.Duration)
  161. }
  162. //if conn.postgresParser == nil {
  163. // conn.postgresParser = l7.NewPostgresParser()
  164. //}
  165. //query := conn.postgresParser.Parse(r.Payload)
  166. //trace.PostgresQuery(query, r.Status.Error(), r.Duration)
  167. if c.l7Attach && c.valuableTrace(r.TraceId) {
  168. if conn.postgresParser == nil {
  169. conn.postgresParser = l7.NewPostgresParser()
  170. }
  171. query := conn.postgresParser.Parse(r.Payload)
  172. //trace.MysqlQuery(query, r.Status.Error(), r.Duration)
  173. //apmTrace, ok := c.getTrace(r.TraceId)
  174. apmTrace, err := c.getOrInitTrace(r.TraceId)
  175. //fmt.Println("mysql r.TraceId:", r.TraceId)
  176. //fmt.Println("ok:", ok)
  177. //fmt.Println("traceMap:", len(c.traceMap))
  178. if err == nil {
  179. //apmTrace.MysqlTraceQuery(query, r.Status.Error(), r.Duration, conn.ActualDest)
  180. //apmTrace.PostGreSqlTraceQueryEvent(query, r, conn.ActualDest)
  181. apmTrace.SQLTraceQueryEvent(l7.ProtocolPostgres, semconv.DBSystemPostgreSQL, query, r, conn.ActualDest)
  182. c.SendEvent(apmTrace, r.TraceId)
  183. }
  184. }
  185. case l7.ProtocolMysql:
  186. if r.Method != l7.MethodStatementClose {
  187. stats.observe(r.Status.String(), "", r.Duration)
  188. }
  189. if c.l7Attach && c.valuableTrace(r.TraceId) {
  190. if conn.mysqlParser == nil {
  191. conn.mysqlParser = l7.NewMysqlParser()
  192. }
  193. query := conn.mysqlParser.Parse(r.Payload, r.StatementId)
  194. //trace.MysqlQuery(query, r.Status.Error(), r.Duration)
  195. //apmTrace, ok := c.getTrace(r.TraceId)
  196. apmTrace, err := c.getOrInitTrace(r.TraceId)
  197. //fmt.Println("mysql r.TraceId:", r.TraceId)
  198. //fmt.Println("ok:", ok)
  199. //fmt.Println("traceMap:", len(c.traceMap))
  200. if err == nil {
  201. //apmTrace.MysqlTraceQuery(query, r.Status.Error(), r.Duration, conn.ActualDest)
  202. //apmTrace.MysqlTraceQueryEvent(query, r, conn.ActualDest)
  203. apmTrace.SQLTraceQueryEvent(l7.ProtocolMysql, semconv.DBSystemMySQL, query, r, conn.ActualDest)
  204. c.SendEvent(apmTrace, r.TraceId)
  205. }
  206. }
  207. case l7.ProtocolDM:
  208. //统计dm的query次数
  209. stats.observe(r.Status.String(), "", r.Duration)
  210. //是否发送数据
  211. if c.l7Attach && c.valuableTrace(r.TraceId) {
  212. if conn.dmParser == nil {
  213. conn.dmParser = l7.NewDmParser()
  214. }
  215. query := conn.dmParser.Parse(r.Payload, r.StatementId)
  216. apmTrace, err := c.getOrInitTrace(r.TraceId)
  217. if err == nil {
  218. //apmTrace.DmTraceQueryEvent(query, r, conn.ActualDest)
  219. apmTrace.SQLTraceQueryEvent(l7.ProtocolDM, semconv.DBSystemDaMengDB, query, r, conn.ActualDest)
  220. c.SendEvent(apmTrace, r.TraceId)
  221. }
  222. }
  223. case l7.ProtocolMemcached:
  224. stats.observe(r.Status.String(), "", r.Duration)
  225. if c.l7Attach && c.valuableTrace(r.TraceId) {
  226. }
  227. //cmd, items := l7.ParseMemcached(r.Payload)
  228. //trace.MemcachedQuery(cmd, items, r.Status.Error(), r.Duration)
  229. case l7.ProtocolRedis:
  230. stats.observe(r.Status.String(), "", r.Duration)
  231. if c.l7Attach && c.valuableTrace(r.TraceId) {
  232. cmd, args := l7.ParseRedis(r.Payload)
  233. //fmt.Println("cmd", cmd)
  234. //fmt.Println("args", args)
  235. //apmTrace, ok := c.getTrace(r.TraceId)
  236. apmTrace, err := c.getOrInitTrace(r.TraceId)
  237. if err == nil {
  238. //apmTrace.RedisTraceQuery(cmd, args, r.Status.Error(), r.Duration)
  239. apmTrace.RedisTraceQueryEvent(cmd, args, r, conn.ActualDest)
  240. c.SendEvent(apmTrace, r.TraceId)
  241. }
  242. }
  243. //trace.RedisQuery(cmd, args, r.Status.Error(), r.Duration)
  244. case l7.ProtocolMongo:
  245. stats.observe(r.Status.String(), "", r.Duration)
  246. if c.l7Attach && c.valuableTrace(r.TraceId) {
  247. }
  248. //query := l7.ParseMongo(r.Payload)
  249. //trace.MongoQuery(query, r.Status.Error(), r.Duration)
  250. case l7.ProtocolKafka, l7.ProtocolCassandra:
  251. stats.observe(r.Status.String(), "", r.Duration)
  252. if c.l7Attach && c.valuableTrace(r.TraceId) {
  253. }
  254. case l7.ProtocolRabbitmq, l7.ProtocolNats:
  255. stats.observe(r.Status.String(), r.Method.String(), 0)
  256. if c.l7Attach && c.valuableTrace(r.TraceId) {
  257. }
  258. case l7.ProtocolDubbo2:
  259. stats.observe(r.Status.String(), "", r.Duration)
  260. if c.l7Attach && c.valuableTrace(r.TraceId) {
  261. }
  262. }
  263. return nil
  264. }
  265. func (c *Container) buildIDs(pid uint32) bool {
  266. c.lock.Lock()
  267. defer c.lock.Unlock()
  268. p := c.processes[pid]
  269. if p != nil {
  270. p.cmdline = string(proc.GetRealCmdline(pid))
  271. }
  272. var sns []string
  273. var sport uint16
  274. for address, val := range c.getListens() {
  275. if val == 1 {
  276. ip := address.IP()
  277. if ip.Is4() && !ip.IsLoopback() {
  278. // 获取端口号
  279. sport = address.Port()
  280. sns = append(sns, fmt.Sprintf("%s:%d", ip, sport))
  281. ////c.instanceID.IntVal, c.instanceID.HashtVal, _ =
  282. //c.AppInfo.Sn = ip.String()
  283. //c.AppInfo.Sport = int(port)
  284. //strInstanceID := utils.BuildInt64ID(fmt.Sprintf("%s:%d", ip.String(), port))
  285. //fmt.Println(port)
  286. ////os.Exit(1)
  287. //c.AppInfo.InstanceIdHash.IntVal, _ = strInstanceID.ToInt64()
  288. //c.AppInfo.InstanceIdHash.HashtVal = strInstanceID.ToHashByte()
  289. ////c.AppInfo.InstanceId = c.instanceID.IntVal
  290. //strAgentID := utils.BuildInt64ID(fmt.Sprintf("%s:%s", strInstanceID, string(proc.GetExe(pid))))
  291. //c.AppInfo.AgentId, _ = strAgentID.ToInt64()
  292. //c.AppInfo.CodeType = c.GetCodeTypeFromCache(pid)
  293. //return true
  294. }
  295. }
  296. }
  297. if len(sns) > 0 {
  298. //c.instanceID.IntVal, c.instanceID.HashtVal, _ =
  299. snsStr := strings.Join(sns, ",")
  300. c.AppInfo.Sn = snsStr
  301. c.AppInfo.Sport = int(sport)
  302. strInstanceID := utils.BuildInt64ID(fmt.Sprintf("%s:%d", c.AppInfo.Sn, sport))
  303. c.AppInfo.InstanceIdHash.IntVal, _ = strInstanceID.ToInt64()
  304. c.AppInfo.InstanceIdHash.HashtVal = strInstanceID.ToHashByte()
  305. strAgentID := utils.BuildInt64ID(fmt.Sprintf("%s:%s", utils.GetHostIP(), string(proc.GetExe(pid))))
  306. c.AppInfo.AgentId, _ = strAgentID.ToInt64()
  307. c.AppInfo.CodeType = c.GetCodeTypeFromCache(pid)
  308. return true
  309. }
  310. return false
  311. }
  312. func (c *Container) ReBuildIds(pid uint32) {
  313. c.lock.Lock()
  314. defer c.lock.Unlock()
  315. var sns []string
  316. var sport uint16
  317. for address, val := range c.getListens() {
  318. if val == 1 {
  319. ip := address.IP()
  320. if ip.Is4() && !ip.IsLoopback() {
  321. // 获取端口号
  322. sport = address.Port()
  323. sns = append(sns, fmt.Sprintf("%s:%d", ip, sport))
  324. }
  325. }
  326. }
  327. if len(sns) > 0 {
  328. snsStr := strings.Join(sns, ",")
  329. c.AppInfo.Sn = snsStr
  330. c.AppInfo.Sport = int(sport)
  331. strInstanceID := utils.BuildInt64ID(fmt.Sprintf("%s:%d", c.AppInfo.Sn, sport))
  332. c.AppInfo.InstanceIdHash.IntVal, _ = strInstanceID.ToInt64()
  333. c.AppInfo.InstanceIdHash.HashtVal = strInstanceID.ToHashByte()
  334. strAgentID := utils.BuildInt64ID(fmt.Sprintf("%s:%s", utils.GetHostIP(), string(proc.GetExe(pid))))
  335. c.AppInfo.AgentId, _ = strAgentID.ToInt64()
  336. c.AppInfo.CodeType = c.GetCodeTypeFromCache(pid)
  337. }
  338. }
  339. func (c *Container) StackProcess(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  340. c.lock.Lock()
  341. defer c.lock.Unlock()
  342. // get the associated uprobe
  343. uprobe, err := c.GetUprobe(event, tracer)
  344. if err != nil {
  345. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  346. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  347. return
  348. }
  349. if event.TraceId <= 0 {
  350. fmt.Println("StackProcess TraceId id 0")
  351. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  352. return
  353. }
  354. // fmt.Printf("StackProcess 函数入口开始处理 fun:TraceId:%lld, Funcname:%s, time: %lld\n", event.TraceId, uprobe.Funcname, event.TimeNsEnd-event.TimeNsStart)
  355. stackFun := ebpftracer.StackFunEvent{}
  356. stackFun.Uprobe = &uprobe
  357. stackFun.StackEvent = event
  358. apmTrace, ok := c.getTrace(event.TraceId)
  359. if ok {
  360. apmTrace.FunAdd(stackFun)
  361. }
  362. }
  363. func byteExtractString(nameString [100]byte) string {
  364. n := bytes.IndexFunc(nameString[:], func(r rune) bool {
  365. return r == 0 || r < 32 || r > 126 // 截取到第一个零值或非打印字符
  366. })
  367. if n == -1 {
  368. n = len(nameString) // 没找到零值或非打印字符,使用数组长度
  369. }
  370. return string(nameString[:n])
  371. }
  372. func (c *Container) StackProcess2(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  373. c.lock.Lock()
  374. defer c.lock.Unlock()
  375. // get the associated uprobe
  376. switch event.Location {
  377. case 0: // ret
  378. Funcname := ""
  379. if event.Type != uint64(CodeTypeJava) {
  380. uprobe, err := c.GetUprobe(event, tracer)
  381. if err != nil {
  382. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  383. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  384. return
  385. }
  386. Funcname = uprobe.Funcname
  387. } else {
  388. ClassName := byteExtractString(event.ClassName)
  389. MethedName := byteExtractString(event.MethedName)
  390. Funcname = ClassName + "." + MethedName
  391. }
  392. if event.TraceId <= 0 {
  393. fmt.Println("StackProcess TraceId id 0")
  394. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  395. return
  396. }
  397. //fmt.Printf("StackProcess 函数入口开始处理 fun:TraceId:%lld, Funcname:%s, time: %lld\n", event.TraceId, uprobe.Funcname, event.TimeNsEnd-event.TimeNsStart)
  398. apmTrace, err := c.getOrInitTrace(event.TraceId)
  399. if err == nil {
  400. //fmt.Println("append FuncTraceQuery fun:", event.TraceId, uprobe.Funcname, event.Pid)
  401. duration := event.TimeNsEnd - event.TimeNsStart
  402. apmTrace.FuncTraceQuery(Funcname, time.Duration(duration), event.TimeNsStart, event.TimeNsEnd)
  403. c.SendEvent(apmTrace, event.TraceId)
  404. }
  405. }
  406. }
  407. // ResolveAddress returns the symbol(s) and offset of the given address.
  408. func (c *Container) ResolveAddress(addr uint64, symbols []elf.Symbol) (syms []elf.Symbol, offset uint, err error) {
  409. if addr == 0 {
  410. // err = errors.Wrapf(SymbolNotFoundError, "0")
  411. return
  412. }
  413. // symbols, _, err := e.Symbols()
  414. if err != nil {
  415. return
  416. }
  417. idx := sort.Search(len(symbols), func(i int) bool { return symbols[i].Value > addr })
  418. if idx == 0 {
  419. // err = errors.Wrap(SymbolNotFoundError, fmt.Sprintf("%x", addr))
  420. return
  421. }
  422. // why diff symbol may contains the same addr?
  423. sym := symbols[idx-1]
  424. for i := idx - 1; i >= 0 && symbols[i].Value == sym.Value; i-- {
  425. syms = append(syms, symbols[i])
  426. }
  427. for i := idx; i < len(symbols) && symbols[i].Value == sym.Value; i++ {
  428. syms = append(syms, symbols[i])
  429. }
  430. return syms, uint(addr - sym.Value), nil
  431. }
  432. type MemoryMap struct {
  433. Start, End uint64
  434. }
  435. // ReadFirstLineOfMapsFile reads the first line of /proc/<pid>/maps file and return the memory map as a MemoryMap struct
  436. func ReadFirstLineOfMapsFile(pid string) (*MemoryMap, error) {
  437. file, err := os.Open(fmt.Sprintf("/proc/%s/maps", pid))
  438. if err != nil {
  439. return nil, err
  440. }
  441. defer file.Close()
  442. scanner := bufio.NewScanner(file)
  443. if scanner.Scan() {
  444. fields := strings.Fields(scanner.Text())
  445. addresses := strings.Split(fields[0], "-")
  446. if len(addresses) != 2 {
  447. return nil, errors.New("unexpected format in /proc/<pid>/maps")
  448. }
  449. start, err := strconv.ParseUint(addresses[0], 16, 64)
  450. if err != nil {
  451. return nil, err
  452. }
  453. end, err := strconv.ParseUint(addresses[1], 16, 64)
  454. if err != nil {
  455. return nil, err
  456. }
  457. return &MemoryMap{
  458. Start: start,
  459. End: end,
  460. }, nil
  461. }
  462. if err := scanner.Err(); err != nil {
  463. return nil, err
  464. }
  465. return nil, errors.New("empty /proc/<pid>/maps")
  466. }
  467. func (c *Container) GetUprobe(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) (uprobe tracer.Uprobe, err error) {
  468. //fmt.Println("GetUprobe entory:")
  469. memoryMap, _ := ReadFirstLineOfMapsFile(strconv.Itoa(int(event.Pid)))
  470. Address := event.Ip - memoryMap.Start
  471. // fmt.Printf("memoryMap.Start: %x, event.Ip: %x, Address: %x\n", memoryMap.Start, event.Ip, Address)
  472. for _, fun := range c.UprobesMap {
  473. funAddress := fun.Address + fun.AbsOffset
  474. // fmt.Printf("GetUprobeGetUprobeGetUprobe:fun.Address %x, fun.AbsOffset: %x\n", fun.Address, fun.AbsOffset)
  475. if funAddress == Address {
  476. // fmt.Printf("---GetUprobeGetUprobeGetUprobe: %x, event.Ip: %x ---- %s--%x\n", memoryMap.Start, event.Ip, fun.Funcname, fun.Address)
  477. return fun, nil
  478. }
  479. }
  480. syms, _, err := c.ResolveAddress(event.Ip, tracer.Symbols)
  481. if err != nil {
  482. return
  483. }
  484. for _, sym := range syms {
  485. //fmt.Println("GetUprobeGetUprobeGetUprobe: %s+%d", sym.Name, offset)
  486. uprobe, ok := tracer.UprobesMap[fmt.Sprintf("%s-%s", sym.Name, sym.Value)]
  487. if ok {
  488. return uprobe, nil
  489. }
  490. }
  491. err = errors.New("uprobe not found")
  492. return
  493. }
  494. func (c *Container) GetAppInfo() AppInfo {
  495. return c.AppInfo
  496. }
  497. // 可注入前置
  498. func (c *Container) checkEventReady() bool {
  499. c.lock.Lock()
  500. defer c.lock.Unlock()
  501. return c.l7EventReady
  502. }
  503. func (c *Container) eventReady() {
  504. c.lock.Lock()
  505. defer c.lock.Unlock()
  506. c.l7EventReady = true
  507. }
  508. // uprobe前置
  509. func (c *Container) Isl7AttachSuccess() bool {
  510. c.lock.Lock()
  511. defer c.lock.Unlock()
  512. return c.l7Attach
  513. }
  514. func (c *Container) l7AttachSuccess() {
  515. c.lock.Lock()
  516. defer c.lock.Unlock()
  517. c.l7Attach = true
  518. }
  519. func (c *Container) ctrlStack(r *Registry, pid uint32) {
  520. resp, err := c.GetCodeSetting(r)
  521. if err != nil {
  522. klog.WithField("pid", pid).WithError(err).Error("[ctrlStack] GetCodeSetting failed.")
  523. return
  524. }
  525. if resp.BlackWhiteSettings.CollectStack == OPEN_STACK {
  526. // 有黑白名单规则 &&
  527. // 之前有注入 先卸载再注入
  528. // 之前没注入 直接注入
  529. // 没有有黑白名单 直接卸载
  530. if c.hasStackRule(resp) {
  531. if c.stackRuleUpdate(resp) {
  532. // 重新注入
  533. err = c.DetachStack(pid, APP_UNINSTALL)
  534. if err != nil {
  535. klog.WithError(err).Errorf("[ctrlStack][end] Failed detach stack trace!")
  536. }
  537. }
  538. klog.WithField("pid", pid).Infoln("[ctrlStack] Attach app stack.")
  539. c.saveWhiteStackSettingInfo(resp)
  540. err = c.AttachStack(r.tracer, pid)
  541. if err != nil {
  542. c.AppInfo.SetAppStackError()
  543. klog.WithField("pid", pid).WithError(err).Errorf("[ctrlStack][end] Failed attach stack trace!")
  544. }
  545. } else {
  546. if c.noOrigRule() {
  547. return
  548. }
  549. c.saveWhiteStackSettingInfo(resp)
  550. // 关闭堆栈
  551. err = c.DetachStack(pid, APP_UNINSTALL)
  552. if err != nil {
  553. klog.WithError(err).Errorf("[ctrlStack][end] Failed detach stack trace!")
  554. }
  555. }
  556. } else {
  557. if c.noOrigRule() {
  558. return
  559. }
  560. c.saveWhiteStackSettingInfo(resp)
  561. // 关闭堆栈
  562. err = c.DetachStack(pid, APP_UNINSTALL)
  563. if err != nil {
  564. klog.WithError(err).Errorf("[ctrlStack][end] Failed detach stack trace!")
  565. }
  566. }
  567. }
  568. func (c *Container) verifyAttachConditions(r *Registry, pid uint32) (bool, int) {
  569. p := c.processes[pid]
  570. if p != nil && c.checkEventReady() {
  571. codeType := c.GetCodeTypeFromCache(pid)
  572. if codeType.IsUnknownCode() {
  573. klog.WithField("pid", pid).Debug("[verify] unknown language.")
  574. return false, 0
  575. }
  576. cmdline := p.GetCmdline()
  577. if len(cmdline) == 0 {
  578. return false, 0
  579. }
  580. //whiteListByCode := r.getWhiteListByCodeType(codeType)
  581. whiteListByCode := r.getWhiteListAll()
  582. //klog.WithField("pid", pid).WithField("codeType", codeType.String()).
  583. // Infof("[verify] white list %v", utils.ToString(whiteListByCode))
  584. // 当前语言的白名单规则
  585. for _, setting := range whiteListByCode {
  586. ruleVal := setting.Filters
  587. if ruleVal == "" {
  588. continue
  589. }
  590. // 判断规则
  591. if strings.Contains(cmdline, ruleVal) {
  592. c.WhiteSettingInfo.AppName = setting.AppName
  593. c.WhiteSettingInfo.Filters = setting.Filters
  594. klog.WithField("pid", pid).
  595. WithField("codeType", codeType.String()).
  596. WithField("ruleVal", ruleVal).
  597. WithField("cmdline", cmdline).
  598. //WithField("stack", setting.OpenStack).
  599. WithField("white list", utils.ToString(whiteListByCode)).
  600. Infoln("[verify] check successful.")
  601. return true, 0
  602. }
  603. }
  604. }
  605. return false, 0
  606. }
  607. // 1.卸载入口
  608. func (c *Container) Detach(pid uint32, detachType APP_TYPE) {
  609. c.lock.Lock()
  610. defer c.lock.Unlock()
  611. if p := c.processes[pid]; p != nil {
  612. err := c.DetachUprobes(pid, detachType)
  613. if err != nil {
  614. klog.WithError(err).Errorln("DetachUprobes Error.")
  615. }
  616. err = c.DetachStack(pid, detachType)
  617. if err != nil {
  618. klog.WithError(err).Errorln("DetachStack Error.")
  619. }
  620. // 关闭7层监控
  621. c.l7Attach = false
  622. // 变更应用状态
  623. if err != nil {
  624. detachType = detachType.Error()
  625. }
  626. c.AppInfo.SetAppStatus(detachType)
  627. }
  628. }
  629. // 1.1卸载uprobe
  630. func (c *Container) DetachUprobes(pid uint32, detachType APP_TYPE) error {
  631. // close uprobe
  632. if p := c.processes[pid]; p != nil {
  633. for _, u := range p.uprobes {
  634. err := u.Close()
  635. if err != nil {
  636. return err
  637. }
  638. }
  639. p.uprobes = []link.Link{}
  640. switch detachType {
  641. case APP_UNINSTALL:
  642. codeType := c.GetCodeTypeFromCache(pid)
  643. switch codeType {
  644. case CodeTypeJava:
  645. p.jvmAttachOnce = false
  646. case CodeTypeGo:
  647. p.goTlsUprobesChecked = false
  648. p.openSslUprobesChecked = false
  649. default:
  650. }
  651. case APP_UPROBE_ERROR:
  652. klog.Infof("[DetachUprobes] ERROR_DETACH for pid %d", pid)
  653. default:
  654. }
  655. } else {
  656. return fmt.Errorf("[DetachUprobes] cannot find uprobe for pid %d", pid)
  657. }
  658. return nil
  659. }
  660. // 1.2卸载堆栈
  661. func (c *Container) DetachStack(pid uint32, detachType APP_TYPE) error {
  662. if p := c.processes[pid]; p != nil {
  663. var err error
  664. codeType := c.GetCodeTypeFromCache(pid)
  665. switch codeType {
  666. // 1.2.1 卸载 jvm堆栈
  667. case CodeTypeJava:
  668. err = c.detachJvmStack(pid)
  669. default:
  670. err = p.closeStackUprobes()
  671. }
  672. if err != nil {
  673. klog.WithError(err).Errorln("[detachStack] failed to detach stack")
  674. return err
  675. }
  676. p.stackAttachOnce = false
  677. } else {
  678. return fmt.Errorf("[DetachStack] cannot find uprobe for pid %d", pid)
  679. }
  680. return nil
  681. }
  682. // 1.2.1 卸载 jvm堆栈
  683. func (c *Container) detachJvmStack(pid uint32) error {
  684. if p := c.processes[pid]; p != nil {
  685. //if p.stackStatus.IsStackUprobesSuccess() || len(p.stackUprobes) > 0 {
  686. //}
  687. // 卸载 JavaAgent
  688. var err error
  689. if p.stackStatus.IsJattachSuccess() {
  690. // 卸载堆栈probes
  691. err = p.closeStackUprobes()
  692. if err != nil {
  693. klog.WithError(err).Errorf("[detachJvmStack] closeStackUprobes")
  694. }
  695. err = p.uninstallJavaAgent()
  696. if err != nil {
  697. klog.WithError(err).Errorf("[detachJvmStack] uninstallJavaAgent")
  698. }
  699. }
  700. return err
  701. }
  702. return nil
  703. }
  704. func (c *Container) getRootfs() string {
  705. if c.metadata != nil && c.metadata.rootfs != "" {
  706. return path.Join(*flags.HostDirPathPrefix, c.metadata.rootfs)
  707. }
  708. return ""
  709. }
  710. func (c *Container) BuildActiveApps(runtimeApps map[uint32]AppStatusInfo, pid uint32) {
  711. if c.AppInfo.AppName != "" {
  712. detail := AppStatusInfo{
  713. Pid: pid,
  714. ProcName: c.containerName,
  715. AppName: c.AppInfo.AppName,
  716. Language: c.AppInfo.CodeType.String(),
  717. AppID: c.AppInfo.AppIdHash.IntVal,
  718. AgentID: c.AppInfo.AgentId,
  719. InstanceID: c.AppInfo.InstanceIdHash.IntVal,
  720. Sn: c.AppInfo.Sn,
  721. Sport: c.AppInfo.Sport,
  722. RegisterAt: time.Unix(c.AppInfo.RegisterAt, 0).Format("060102 15:04:05"),
  723. PreStatus: c.AppInfo.PreStatus,
  724. Status: c.AppInfo.Status,
  725. Rule: c.WhiteSettingInfo.Filters,
  726. }
  727. detail.Rule = fmt.Sprintf("%s|%d", c.WhiteSettingInfo.Filters, c.WhiteSettingInfo.WhiteStackSettingInfo.OpenStack)
  728. if c.AppInfo.UpdateAt != 0 {
  729. detail.UpdateAt = time.Unix(c.AppInfo.UpdateAt, 0).Format("060102 15:04:05")
  730. }
  731. p := c.processes[pid]
  732. if p != nil {
  733. detail.StackStatus = p.stackStatus.String()
  734. detail.StackStatus += fmt.Sprintf("|vFailed:%v", p.versionFailed)
  735. }
  736. runtimeApps[pid] = detail
  737. }
  738. }
  739. func (c *Container) AgentCtrl(r *Registry, pid uint32) {
  740. var err error
  741. verifyAttachConditions, _ := c.verifyAttachConditions(r, pid)
  742. // UNINSTALL
  743. if r.isFusing && c.Isl7AttachSuccess() {
  744. c.Detach(pid, APP_FUSE)
  745. return
  746. }
  747. // verify UNINSTALL
  748. if !verifyAttachConditions && c.Isl7AttachSuccess() {
  749. c.Detach(pid, APP_UNINSTALL)
  750. return
  751. }
  752. if verifyAttachConditions {
  753. err = c.RegisterAppInfo(r, pid)
  754. if err != nil {
  755. klog.WithError(err).Errorf("[AgentCtrl] Failed registerAppInfo.")
  756. return
  757. }
  758. klog.WithField("pid", pid).Infoln("[AgentCtrl] Attach uprobes.")
  759. err = c.AttachUprobes(r.tracer, pid)
  760. if err != nil {
  761. klog.WithField("pid", pid).WithError(err).Errorf("[AgentCtrl] Failed attach uprobes error!")
  762. return
  763. } else {
  764. klog.WithField("pid", pid).Infoln("[AgentCtrl] Attach uprobes success!")
  765. }
  766. // 堆栈控制
  767. c.ctrlStack(r, pid)
  768. }
  769. }