apm_exporter.go 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142
  1. package otlptrace
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "fmt"
  6. . "github.com/coroot/coroot-node-agent/ebpftracer"
  7. "github.com/coroot/coroot-node-agent/ebpftracer/l7"
  8. "github.com/coroot/coroot-node-agent/utils"
  9. klog "github.com/sirupsen/logrus"
  10. "math"
  11. "net/url"
  12. "sort"
  13. "strconv"
  14. "strings"
  15. "sync"
  16. "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform"
  17. tracesdk "go.opentelemetry.io/otel/sdk/trace"
  18. tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
  19. )
  20. const (
  21. APP_SERVICE_TYPE = "APPLICATION"
  22. SQL_SERVICE_TYPE = "SQL"
  23. NOSQL_SERVICE_TYPE = "NOSQL"
  24. HTTP_SERVICE_TYPE = "HTTP"
  25. NET_SERVICE_TYPE = "L7_NET"
  26. MQ_SERVICE_TYPE = "MQ"
  27. )
  28. const (
  29. GO_SERVICE_NAME = "GO"
  30. MYSQL_SERVICE_NAME = "MYSQL"
  31. DM_SERVICE_NAME = "DM"
  32. REDIS_SERVICE_NAME = "REDIS"
  33. HTTP_SERVICE_NAME = "HTTPCLIENT"
  34. POSTGRESQL_SERVICE_NAME = "POSTGRESQL"
  35. KAFKA_SERVICE_NAME = "KAFKA"
  36. )
  37. type apmTraceSpan tracesdk.ReadOnlySpan
  38. // GO:0:10154813500555812:5450531005555981:5610250100539899:ee022542c3940f1b:1001025098564810:888ceb3df1bdbe2c:110
  39. type RootDataT struct {
  40. AccountId int `json:"account_id"`
  41. AgentId int64 `json:"agent_id"`
  42. AgentVersion string `json:"agent_version"`
  43. AppId int64 `json:"app_id"`
  44. AppIdFrom int64 `json:"app_id_from"` // from header app_id
  45. AppName string `json:"app_name"`
  46. CalledId int64 `json:"called_id"` // from header assumed_app_id
  47. ClientIp string `json:"client_ip"`
  48. CollTime uint64 `json:"coll_time"`
  49. Cpu int `json:"cpu"`
  50. Custom string `json:"custom"`
  51. HostId int64 `json:"host_id"`
  52. HostName string `json:"host_name"`
  53. HttpCode int64 `json:"http_code"`
  54. HttpMethod string `json:"http_method"`
  55. InstanceId int64 `json:"instance_id"`
  56. InstanceIdFrom int64 `json:"instance_id_from"` // from header instance_id
  57. LocalPort int64 `json:"local_port"`
  58. Maps []MapInfoT `json:"maps"`
  59. MemU int `json:"mem_u"`
  60. MemUP int `json:"mem_u_p"`
  61. OperType string `json:"oper_type"`
  62. Parameters []ParamStruct `json:"parameters,omitempty"`
  63. ParentTaskName int `json:"parent_task_name"`
  64. Period int `json:"period"`
  65. RespTime uint64 `json:"resp_time"`
  66. Sampling int `json:"sampling"`
  67. ServiceName string `json:"service_name"`
  68. ServiceType string `json:"service_type"`
  69. Sip string `json:"sip"`
  70. Sn string `json:"sn"`
  71. SpanIdFrom string `json:"span_id_from"` // from header span_id
  72. Sport int64 `json:"sport"`
  73. TId int `json:"t_id"`
  74. TName string `json:"t_name"`
  75. TraceId string `json:"trace_id"` // from header trace_id
  76. TransIds []interface{} `json:"trans_ids"`
  77. TypeFrom string `json:"type_from"`
  78. Uri string `json:"uri"`
  79. UserDir int `json:"user_dir"`
  80. VipIds []interface{} `json:"vip_ids"`
  81. SrcAddr string `json:"src_addr"`
  82. DestinationAddr string `json:"destination_addr"`
  83. }
  84. // ParamStruct 定义目标结构
  85. type ParamStruct struct {
  86. Name string `json:"name"`
  87. Values []string `json:"values"`
  88. }
  89. type MapInfoT struct {
  90. Dbn string `json:"dbn,omitempty"`
  91. Exception int `json:"exception,omitempty"`
  92. ExceptionMsg string `json:"exception_msg,omitempty"`
  93. ExceptionStack string `json:"exception_stack,omitempty"`
  94. Ip string `json:"ip,omitempty"`
  95. Level int `json:"level"`
  96. MethodDesc string `json:"method_desc,omitempty"`
  97. MethodName string `json:"method_name"`
  98. Nid int `json:"nid"`
  99. OperType string `json:"oper_type,omitempty"`
  100. Pid int `json:"pid"`
  101. Port int64 `json:"port,omitempty"`
  102. Ps []string `json:"ps,omitempty"`
  103. PureTime uint64 `json:"pure_time"`
  104. ServiceName string `json:"service_name"`
  105. ServiceType string `json:"service_type"`
  106. StartTime uint64 `json:"-"`
  107. EndTime uint64 `json:"-"`
  108. StartTimeMs uint64 `json:"start_time"`
  109. EndTimeMs uint64 `json:"end_time"`
  110. WallTime uint64 `json:"wall_time"`
  111. Schema string `json:"schema,omitempty"`
  112. AssumedAppId int64 `json:"assumed_app_id,omitempty"`
  113. Uri string `json:"uri,omitempty"`
  114. SpanId string `json:"span_id,omitempty"`
  115. SrcAddr string `json:"src_addr,omitempty"`
  116. DestinationAddr string `json:"destination_addr,omitempty"`
  117. Flow int64 `json:"flow,omitempty"`
  118. }
  119. type TraceMapT struct {
  120. RootData RootDataT
  121. Index int
  122. lock *sync.RWMutex
  123. TheEnd bool
  124. }
  125. var TraceRootMap map[string]*TraceMapT
  126. func init() {
  127. TraceRootMap = make(map[string]*TraceMapT)
  128. //go func() {
  129. // for {
  130. // //fmt.Println(G_sdl)
  131. // time.Sleep(5 * time.Second)
  132. // }
  133. //}()
  134. }
  135. var G_sdl int
  136. func tracetransformData(sdl []tracesdk.ReadOnlySpan) map[int][]RootDataT {
  137. //G_sdl += len(sdl)
  138. if len(sdl) == 0 {
  139. return nil
  140. }
  141. // 多次请求 sdl
  142. sendDataMap := make(map[int][]RootDataT)
  143. //sendData := []RootDataT{}
  144. for _, sd := range sdl {
  145. if sd == nil {
  146. continue
  147. }
  148. //traceId := sd.SpanContext().TraceID().String()
  149. //fmt.Println("------event_num---- "+sd.Name(), "--->", len(sd.Events())) // 一次请求完整数据
  150. // 构建map *RootDataT
  151. var rootData RootDataT
  152. rootData = initRootDataFromEvent()
  153. // build http入口 MapInfoT
  154. code_type := buildAppMapFromEvent(&rootData, sd)
  155. // 构建maps
  156. for _, event := range sd.Events() {
  157. //aaa, _ := json.Marshal(event)
  158. //fmt.Println("event.info", string(aaa))
  159. mNode := buildMapNodeFromEvent(event)
  160. switch EventType(event.EventType) {
  161. // stack
  162. case EventTypeFunEnt:
  163. // l7 event
  164. case EventTypeL7Request:
  165. switch l7.Protocol(event.ProtocolType) {
  166. case l7.ProtocolHTTP:
  167. buildHttpMapFromEvent(&mNode, event)
  168. case l7.ProtocolDNS:
  169. buildDNSMapEvent(&mNode, event)
  170. case l7.ProtocolMysql:
  171. buildSQLMapEvent(&mNode, event)
  172. case l7.ProtocolRedis:
  173. buildRedisMapEvent(&mNode, event)
  174. // dm
  175. case l7.ProtocolDM:
  176. buildSQLMapEvent(&mNode, event)
  177. case l7.ProtocolPostgres:
  178. buildSQLMapEvent(&mNode, event)
  179. case l7.ProtocolKafka:
  180. buildMQMapEvent(&mNode, event)
  181. }
  182. }
  183. rootData.Maps = append(rootData.Maps, mNode)
  184. //fmt.Println(event.Name)
  185. //buildAndAssemblyMapFromEvent(event, rootData)
  186. }
  187. buildLevelFromEvent(&rootData)
  188. sendDataMap[code_type] = append(sendDataMap[code_type], rootData)
  189. //a, _ := json.Marshal(rootData)
  190. //fmt.Println(string(a))
  191. //sendData = append(sendData, rootData)
  192. //if _, ok := TraceRootMap[traceId]; !ok {
  193. //TraceRootMap[traceId] = &TraceMapT{RootData: initRootData(traceId), Index: 1}
  194. //}
  195. //TraceRootMap[traceId].Index++
  196. //buildAndAssemblyMap(sd, TraceRootMap[traceId])
  197. }
  198. // 发送完整数据 | 大量长耗时请求会增加内存占用
  199. //sendData := []RootDataT{}
  200. //for traceId, v := range TraceRootMap {
  201. // if v.TheEnd {
  202. // buildLevel(v)
  203. // sendData = append(sendData, v.RootData)
  204. // delete(TraceRootMap, traceId)
  205. // //fmt.Println("the end!")
  206. // } else {
  207. // //fmt.Println("not end!")
  208. // }
  209. //}
  210. //Transform the categorized map into a slice
  211. data, _ := json.Marshal(sendDataMap)
  212. klog.Info(string(data))
  213. //fmt.Println(len(sendData))
  214. //fmt.Println("sdl len:", len(sdl))
  215. return sendDataMap
  216. }
  217. type TimeMap struct {
  218. Time uint64
  219. Type int
  220. Map *MapInfoT
  221. }
  222. //type TraceMapT struct {
  223. // RootData RootDataT
  224. // Index int
  225. // lock *sync.RWMutex
  226. // TheEnd bool
  227. //}
  228. //func buildLevel(sdl *TraceMapT) {
  229. // nidMap := make(map[int]*MapInfoT)
  230. //
  231. // mapSlice := []TimeMap{}
  232. //
  233. // for i, v := range sdl.RootData.Maps {
  234. // if v.ServiceType == "APPLICATION" {
  235. // continue
  236. // }
  237. // nidMap[v.Nid] = &sdl.RootData.Maps[i]
  238. // timeStartMap := TimeMap{
  239. // Time: v.StartTime,
  240. // Type: 0,
  241. // Map: &sdl.RootData.Maps[i],
  242. // }
  243. // mapSlice = append(mapSlice, timeStartMap)
  244. // timeEndMap := TimeMap{
  245. // Time: v.EndTime,
  246. // Type: 1,
  247. // Map: &sdl.RootData.Maps[i],
  248. // }
  249. // mapSlice = append(mapSlice, timeEndMap)
  250. // }
  251. // sort.Slice(mapSlice, func(i, j int) bool {
  252. // return mapSlice[i].Time < mapSlice[j].Time
  253. // })
  254. //
  255. // funStack := []TimeMap{}
  256. //
  257. // currentNid := 1
  258. // Nid := 2
  259. // level := 2
  260. //
  261. // for _, v := range mapSlice {
  262. // // fmt.Println("SliceSliceindex", k, "value", v.Time, v.Type, v.Map.MethodName, v.Map.Nid)
  263. // if v.Type == 0 {
  264. // // 函数入口
  265. // funStack = append(funStack, v)
  266. // v.Map.Pid = currentNid
  267. // v.Map.Level = level
  268. // v.Map.Nid = Nid
  269. // currentNid = Nid
  270. // level += 1
  271. // Nid += 1
  272. // } else if v.Type == 1 {
  273. // // 函数出口
  274. // len := len(funStack)
  275. // funStack = funStack[:len-1]
  276. // if (len - 2) < 0 {
  277. // currentNid = 1
  278. // } else {
  279. // currentNid = funStack[len-2].Map.Nid
  280. // }
  281. //
  282. // level -= 1
  283. // }
  284. // }
  285. //}
  286. func buildLevelFromEvent(sdl *RootDataT) {
  287. nidMap := make(map[int]*MapInfoT)
  288. mapSlice := []TimeMap{}
  289. for i, v := range sdl.Maps {
  290. if v.ServiceType == "APPLICATION" {
  291. continue
  292. }
  293. nidMap[v.Nid] = &sdl.Maps[i]
  294. timeStartMap := TimeMap{
  295. Time: v.StartTime,
  296. Type: 0,
  297. Map: &sdl.Maps[i],
  298. }
  299. mapSlice = append(mapSlice, timeStartMap)
  300. timeEndMap := TimeMap{
  301. Time: v.EndTime,
  302. Type: 1,
  303. Map: &sdl.Maps[i],
  304. }
  305. mapSlice = append(mapSlice, timeEndMap)
  306. }
  307. sort.Slice(mapSlice, func(i, j int) bool {
  308. return mapSlice[i].Time < mapSlice[j].Time
  309. })
  310. funStack := []TimeMap{}
  311. currentNid := 1
  312. Nid := 2
  313. level := 2
  314. for _, v := range mapSlice {
  315. //klog.Debugln("SliceSliceindex", k, "value", v.Time, v.Type, v.Map.MethodName, v.Map.Nid)
  316. if v.Type == 0 {
  317. // 函数入口
  318. funStack = append(funStack, v)
  319. v.Map.Pid = currentNid
  320. v.Map.Level = level
  321. v.Map.Nid = Nid
  322. currentNid = Nid
  323. level += 1
  324. Nid += 1
  325. } else if v.Type == 1 {
  326. // 函数出口
  327. len := len(funStack)
  328. funStack = funStack[:len-1]
  329. if (len - 2) < 0 {
  330. currentNid = 1
  331. } else {
  332. currentNid = funStack[len-2].Map.Nid
  333. }
  334. level -= 1
  335. }
  336. }
  337. }
  338. //func initRootData(traceId string) RootDataT {
  339. // data := RootDataT{
  340. // AccountId: 110,
  341. // AgentId: 1011005252979954, // TODO 更新 基于 ip:port + process_name + exe路径生成
  342. // AgentVersion: "2.1.0",
  343. // AppId: 5410049101545798, // TODO 更新 基于appname生成
  344. // AppIdFrom: -1,
  345. // AppName: "eBPF-agent", // TODO 更新 ip:port || process_name
  346. // CalledId: -1,
  347. // ClientIp: "",
  348. // CollTime: 0,
  349. // Cpu: 0,
  350. // Custom: "",
  351. // HostId: 10154813500555812,
  352. // HostName: "localhost",
  353. // HttpCode: 0,
  354. // HttpMethod: "",
  355. // InstanceId: 1005051101515357, // TODO 更新 基于ip:port
  356. // InstanceIdFrom: -1,
  357. // Maps: []MapInfoT{},
  358. // MemU: 0,
  359. // MemUP: 0,
  360. // OperType: "",
  361. // Parameters: []interface{}{},
  362. // ParentTaskName: 0,
  363. // Period: -1,
  364. // RespTime: 0,
  365. // Sampling: 0,
  366. // ServiceName: "GO",
  367. // ServiceType: APP_SERVICE_TYPE,
  368. // Sip: "",
  369. // Sn: "",
  370. // SpanIdFrom: "",
  371. // Sport: 0,
  372. // TId: -1,
  373. // TName: "",
  374. // TraceId: traceId,
  375. // TransIds: []interface{}{},
  376. // TypeFrom: "",
  377. // Uri: "",
  378. // UserDir: 0,
  379. // VipIds: []interface{}{},
  380. // }
  381. // return data
  382. //}
  383. func initRootDataFromEvent() RootDataT {
  384. hostID := utils.GetHostID()
  385. accountID := utils.GetAccountID()
  386. data := RootDataT{
  387. // todo AccountId
  388. AccountId: accountID,
  389. AgentId: 0, // 基于 ip:port + process_name + exe路径生成
  390. AgentVersion: "2.1.0",
  391. AppId: 0, // 基于appname生成
  392. AppIdFrom: -1,
  393. AppName: "eBPF-agent", // server配置
  394. CalledId: -1,
  395. ClientIp: "",
  396. CollTime: 0,
  397. Cpu: 0,
  398. Custom: "",
  399. HostId: hostID,
  400. HostName: "localhost",
  401. HttpCode: 0,
  402. HttpMethod: "",
  403. InstanceId: 0, // 基于ip:port
  404. InstanceIdFrom: -1,
  405. Maps: []MapInfoT{},
  406. MemU: 0,
  407. MemUP: 0,
  408. OperType: "",
  409. Parameters: []ParamStruct{},
  410. ParentTaskName: 0,
  411. Period: -1,
  412. RespTime: 0,
  413. Sampling: 0,
  414. ServiceName: "",
  415. ServiceType: APP_SERVICE_TYPE,
  416. Sip: "",
  417. Sn: "",
  418. SpanIdFrom: "",
  419. Sport: 0,
  420. TId: -1,
  421. TName: "",
  422. TraceId: "",
  423. TransIds: []interface{}{},
  424. TypeFrom: "",
  425. Uri: "",
  426. UserDir: 0,
  427. VipIds: []interface{}{},
  428. SrcAddr: "",
  429. DestinationAddr: "",
  430. }
  431. return data
  432. }
  433. func initRootDataJava() RootDataT {
  434. data := RootDataT{
  435. AccountId: 110,
  436. AgentId: 3934815089541000, // TODO 更新 基于 ip:port + process_name + exe路径生成
  437. AgentVersion: "2.21.0",
  438. AppId: 3365853273187618, // TODO 更新 基于appname生成
  439. AppIdFrom: -1,
  440. AppName: "eBPF-javaApplication", // TODO 更新 ip:port || process_name
  441. CalledId: -1,
  442. ClientIp: "",
  443. CollTime: 0,
  444. Cpu: 0,
  445. Custom: "",
  446. HostId: 2315065183171055,
  447. HostName: "localhost",
  448. HttpCode: 0,
  449. HttpMethod: "",
  450. InstanceId: 1128864082033413, // TODO 更新 基于ip:port
  451. InstanceIdFrom: -1,
  452. Maps: []MapInfoT{},
  453. MemU: 0,
  454. MemUP: 0,
  455. OperType: "",
  456. Parameters: []ParamStruct{},
  457. ParentTaskName: 0,
  458. Period: -1,
  459. RespTime: 0,
  460. Sampling: 0,
  461. ServiceName: "TOMCAT",
  462. ServiceType: APP_SERVICE_TYPE,
  463. Sip: "",
  464. Sn: "",
  465. SpanIdFrom: "",
  466. Sport: 0,
  467. TId: -1,
  468. TName: "",
  469. TraceId: "",
  470. TransIds: []interface{}{},
  471. TypeFrom: "",
  472. Uri: "",
  473. UserDir: 0,
  474. VipIds: []interface{}{},
  475. }
  476. return data
  477. }
  478. //func initMapNode(spanSd *tracepb.Span) (MapInfoT, string) {
  479. // mNode := MapInfoT{
  480. // Exception: 0,
  481. // ExceptionMsg: "",
  482. // ExceptionStack: "",
  483. // Ip: "",
  484. // Level: 2,
  485. // Pid: 1,
  486. // Port: 0,
  487. // Ps: []string{},
  488. // ServiceName: "",
  489. // ServiceType: "",
  490. // WallTime: 0,
  491. // }
  492. // mNode.MethodName = spanSd.Name
  493. // mNode.PureTime = (spanSd.EndTimeUnixNano - spanSd.StartTimeUnixNano) / 1e3
  494. // mNode.WallTime = mNode.PureTime
  495. // mNode.StartTime = spanSd.StartTimeUnixNano
  496. // mNode.EndTime = spanSd.EndTimeUnixNano
  497. //
  498. // for _, attr := range spanSd.GetAttributes() {
  499. // fmt.Println(attr.Key, ":", attr.Value.GetValue())
  500. //
  501. // switch attr.Key {
  502. // case "nid":
  503. // mNode.Nid = int(attr.Value.GetIntValue())
  504. // case "pid":
  505. // mNode.Pid = int(attr.Value.GetIntValue())
  506. // case "level":
  507. // mNode.Level = int(attr.Value.GetIntValue())
  508. // }
  509. // }
  510. //
  511. // return mNode, spanSd.Name
  512. //}
  513. func buildMapNodeFromEvent(event tracesdk.Event) MapInfoT {
  514. mNode := MapInfoT{
  515. Exception: 0,
  516. ExceptionMsg: "",
  517. ExceptionStack: "",
  518. Ip: "",
  519. Level: 2,
  520. Pid: 1,
  521. Port: 0,
  522. Ps: []string{},
  523. ServiceName: "",
  524. ServiceType: "",
  525. WallTime: 0,
  526. }
  527. mNode.MethodName = event.Name
  528. //mNode.PureTime = (event.EndTimeUnixNano - event.StartTimeUnixNano) / 1e3
  529. //mNode.WallTime = mNode.PureTime
  530. //mNode.StartTime = spanSd.StartTimeUnixNano
  531. //mNode.EndTime = spanSd.EndTimeUnixNano
  532. for _, attr := range event.Attributes {
  533. //fmt.Println(event.Name, "--->buildMapNodeFromEvent--->", attr.Key, ":", attr.Value.AsInterface())
  534. switch attr.Key {
  535. case "nid":
  536. mNode.Nid = int(attr.Value.AsInt64())
  537. case "pid":
  538. mNode.Pid = int(attr.Value.AsInt64())
  539. case "level":
  540. mNode.Level = int(attr.Value.AsInt64())
  541. case "time.start_at":
  542. mNode.StartTime, mNode.StartTimeMs = cleanNsTime(attr.Value.AsInt64())
  543. case "time.end_at":
  544. mNode.EndTime, mNode.EndTimeMs = cleanNsTime(attr.Value.AsInt64())
  545. case "time.duration":
  546. //mNode.PureTime = uint64(attr.Value.AsInt64()) / 1e3
  547. mNode.WallTime = uint64(attr.Value.AsInt64()) / 1e3
  548. }
  549. }
  550. return mNode
  551. }
  552. func parseURIToParams(input string) (string, []ParamStruct, error) {
  553. // 解析输入 URI
  554. parsedURL, err := url.Parse(input)
  555. if err != nil {
  556. return "", nil, fmt.Errorf("failed to parse URI: %w", err)
  557. }
  558. // 提取查询参数
  559. queryParams := parsedURL.Query()
  560. // 转换为目标结构
  561. var params []ParamStruct
  562. for key, values := range queryParams {
  563. params = append(params, ParamStruct{
  564. Name: key,
  565. Values: values,
  566. })
  567. }
  568. return parsedURL.Path, params, nil
  569. }
  570. // 构建拼装
  571. //func buildAndAssemblyMap(sd apmTraceSpan, traceRoot *TraceMapT) MapInfoT {
  572. // mNode, mapType := initMapNode(span(sd))
  573. // switch mapType {
  574. // case "APPLICATION":
  575. // buildAppMap(&mNode, traceRoot, sd)
  576. // traceRoot.TheEnd = true
  577. // case "HTTP":
  578. // buildHttpMap(&mNode, sd)
  579. // case "Mysql":
  580. // buildMysqlMap(&mNode, sd)
  581. // case "Redis":
  582. // buildRedisMap(&mNode, sd)
  583. // }
  584. // if mapType != "" {
  585. // mNode.Nid = traceRoot.Index
  586. // traceRoot.RootData.Maps = append(traceRoot.RootData.Maps, mNode)
  587. // }
  588. // return mNode
  589. //}
  590. //func buildAndAssemblyMapFromEvent(event tracesdk.Event, traceRoot *RootDataT) MapInfoT {
  591. // mNode := buildMapNodeFromEvent(event)
  592. // switch mapType {
  593. // case "HTTP":
  594. // buildHttpMapFromEvent(mNode, event)
  595. // //case "Mysql":
  596. // // buildMysqlMap(mNode, sd)
  597. // //case "Redis":
  598. // // buildRedisMap(mNode, sd)
  599. // }
  600. // if mapType != "" {
  601. // //mNode.Nid = traceRoot.Index
  602. // traceRoot.Maps = append(traceRoot.Maps, mNode)
  603. // }
  604. // return mNode
  605. //}
  606. //func buildAppMap(mNode *MapInfoT, traceRoot *TraceMapT, sd apmTraceSpan) {
  607. // mNode.ServiceName = GO_SERVICE_NAME
  608. // mNode.ServiceType = APP_SERVICE_TYPE
  609. // mNode.MethodName = "net/http.(*Transport).roundTrip()"
  610. // mNode.Level = 1
  611. // mNode.Pid = 0
  612. // mNode.Nid = 1
  613. // // 构建root节点
  614. // traceRoot.RootData.RespTime = mNode.PureTime
  615. // traceRoot.RootData.CollTime = mNode.StartTime
  616. // traceRoot.Index = 1
  617. // for _, attr := range sd.Attributes() {
  618. // fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  619. // switch attr.Key {
  620. // case "http.uri":
  621. // traceRoot.RootData.Uri = attr.Value.AsString()
  622. // case "http.method":
  623. // traceRoot.RootData.HttpMethod = attr.Value.AsString()
  624. // case "http.status_code":
  625. // traceRoot.RootData.HttpCode = attr.Value.AsInt64()
  626. // case "net.peer.name":
  627. // traceRoot.RootData.ClientIp = attr.Value.AsString()
  628. // traceRoot.RootData.Sip = attr.Value.AsString()
  629. // traceRoot.RootData.Sn = attr.Value.AsString()
  630. // case "net.peer.port":
  631. // traceRoot.RootData.Sport = attr.Value.AsInt64()
  632. // traceRoot.RootData.LocalPort = attr.Value.AsInt64()
  633. // case "server.trace_id_from":
  634. // traceRoot.RootData.TraceId = attr.Value.AsString()
  635. // case "server.called_id":
  636. // traceRoot.RootData.CalledId = attr.Value.AsInt64()
  637. // case "server.instance_id_from":
  638. // traceRoot.RootData.InstanceIdFrom = attr.Value.AsInt64()
  639. // case "server.app_id_from":
  640. // traceRoot.RootData.AppIdFrom = attr.Value.AsInt64()
  641. // case "server.span_id_from":
  642. // traceRoot.RootData.SpanIdFrom = attr.Value.AsString()
  643. // case "server.type_from":
  644. // traceRoot.RootData.TypeFrom = attr.Value.AsString()
  645. // }
  646. // }
  647. //
  648. //}
  649. func buildAppMapFromEvent(traceRoot *RootDataT, sd apmTraceSpan) int {
  650. mNode := MapInfoT{
  651. Exception: 0,
  652. ExceptionMsg: "",
  653. ExceptionStack: "",
  654. Ip: "",
  655. Level: 1,
  656. Pid: 1,
  657. Port: 0,
  658. Ps: []string{},
  659. ServiceName: "",
  660. ServiceType: "",
  661. WallTime: 0,
  662. }
  663. mNode.ServiceName = GO_SERVICE_NAME
  664. mNode.ServiceType = APP_SERVICE_TYPE
  665. mNode.MethodName = "Kernel Endpoint()"
  666. mNode.Level = 1
  667. mNode.Pid = 0
  668. mNode.Nid = 1
  669. var code_type int64
  670. // 构建root节点
  671. //traceRoot.RespTime = mNode.PureTimex
  672. //traceRoot.CollTime = mNode.StartTime
  673. for _, attr := range sd.Attributes() {
  674. klog.Debugln("Appmap:", attr.Key, ":", attr.Value.AsInterface())
  675. switch attr.Key {
  676. case "http.uri":
  677. traceRoot.Uri, traceRoot.Parameters, _ = parseURIToParams(attr.Value.AsString())
  678. case "http.method":
  679. traceRoot.HttpMethod = attr.Value.AsString()
  680. case "http.status_code":
  681. traceRoot.HttpCode = attr.Value.AsInt64()
  682. case "net.peer.name":
  683. // TODO 修改 ClientIp sip获取方式
  684. traceRoot.ClientIp = attr.Value.AsString()
  685. traceRoot.Sip = attr.Value.AsString()
  686. traceRoot.Sn = attr.Value.AsString()
  687. case "net.peer.port":
  688. traceRoot.Sport = attr.Value.AsInt64()
  689. traceRoot.LocalPort = attr.Value.AsInt64()
  690. case "server.trace_id_from":
  691. traceRoot.TraceId = attr.Value.AsString()
  692. case "server.called_id":
  693. traceRoot.CalledId = attr.Value.AsInt64()
  694. case "server.instance_id_from":
  695. traceRoot.InstanceIdFrom = attr.Value.AsInt64()
  696. case "server.app_id_from":
  697. traceRoot.AppIdFrom = attr.Value.AsInt64()
  698. case "server.span_id_from":
  699. traceRoot.SpanIdFrom = attr.Value.AsString()
  700. case "server.type_from":
  701. traceRoot.TypeFrom = attr.Value.AsString()
  702. case "time.start_at":
  703. mNode.StartTime, mNode.StartTimeMs = cleanNsTime(attr.Value.AsInt64())
  704. traceRoot.CollTime = mNode.StartTimeMs
  705. case "time.end_at":
  706. mNode.EndTime, mNode.EndTimeMs = cleanNsTime(attr.Value.AsInt64())
  707. case "time.duration":
  708. traceRoot.RespTime = uint64(attr.Value.AsInt64()) / 1e3
  709. mNode.PureTime = traceRoot.RespTime
  710. mNode.WallTime = uint64(attr.Value.AsInt64()) / 1e3
  711. case "server.code_type":
  712. code_type = attr.Value.AsInt64()
  713. case "server.app_name":
  714. traceRoot.AppName = attr.Value.AsString()
  715. case "server.service_name":
  716. traceRoot.ServiceName = attr.Value.AsString()
  717. mNode.ServiceName = attr.Value.AsString()
  718. case "server.app_id":
  719. traceRoot.AppId = attr.Value.AsInt64()
  720. case "server.agent_id":
  721. traceRoot.AgentId = attr.Value.AsInt64()
  722. case "server.instance_id":
  723. traceRoot.InstanceId = attr.Value.AsInt64()
  724. case "server.src_addr":
  725. traceRoot.SrcAddr = attr.Value.AsString()
  726. case "server.dst_addr":
  727. traceRoot.DestinationAddr = attr.Value.AsString()
  728. }
  729. }
  730. traceRoot.Maps = append(traceRoot.Maps, mNode)
  731. return int(code_type)
  732. }
  733. //func buildHttpMap(mNode *MapInfoT, sd apmTraceSpan) {
  734. // mNode.ServiceName = HTTP_SERVICE_NAME
  735. // mNode.ServiceType = HTTP_SERVICE_TYPE
  736. // mNode.Schema = "http"
  737. // mNode.MethodName = "net/http.serverHandler.ServeHTTP()"
  738. // var descAddr string
  739. // for _, attr := range sd.Attributes() {
  740. // //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  741. // switch attr.Key {
  742. // case "http.ip":
  743. // mNode.Ip = attr.Value.AsString()
  744. // descAddr += mNode.Ip
  745. // case "http.port":
  746. // mNode.Port = attr.Value.AsInt64()
  747. // descAddr += ":" + attr.Value.AsString()
  748. // case "http.uri":
  749. // mNode.Uri = attr.Value.AsString()
  750. // case "http.assumed_app_id":
  751. // mNode.AssumedAppId = attr.Value.AsInt64()
  752. // case "http.span_id":
  753. // mNode.SpanId = attr.Value.AsString()
  754. // }
  755. // }
  756. // //mNode.AssumedAppId = Md5ToInt64(descAddr, 16)
  757. //}
  758. func buildHttpMapFromEvent(mNode *MapInfoT, event tracesdk.Event) {
  759. mNode.ServiceName = HTTP_SERVICE_NAME
  760. mNode.ServiceType = HTTP_SERVICE_TYPE
  761. mNode.Schema = "http"
  762. //mNode.MethodName = "HTTP"
  763. //var descAddr string
  764. var method string
  765. for _, attr := range event.Attributes {
  766. //fmt.Println("HTTP--->", attr.Key, ":", attr.Value.AsInterface())
  767. switch attr.Key {
  768. case "http.ip":
  769. mNode.Ip = attr.Value.AsString()
  770. //descAddr += mNode.Ip
  771. case "http.port":
  772. mNode.Port = attr.Value.AsInt64()
  773. case "http.method":
  774. //mNode.MethodName += " " + attr.Value.AsString()
  775. method = attr.Value.AsString()
  776. //descAddr += ":" + attr.Value.AsString()
  777. case "http.uri":
  778. mNode.Uri = attr.Value.AsString()
  779. //mNode.MethodName += " " + attr.Value.AsString()
  780. case "http.assumed_app_id":
  781. mNode.AssumedAppId = attr.Value.AsInt64()
  782. case "http.span_id":
  783. mNode.SpanId = attr.Value.AsString()
  784. case "time.start_at":
  785. mNode.StartTime = uint64(attr.Value.AsInt64())
  786. case "time.end_at":
  787. mNode.EndTime = uint64(attr.Value.AsInt64())
  788. case "time.duration":
  789. //mNode.PureTime = uint64(attr.Value.AsInt64()) / 1e3
  790. mNode.WallTime = uint64(attr.Value.AsInt64()) / 1e3
  791. case "http.src_addr":
  792. mNode.SrcAddr = attr.Value.AsString()
  793. case "http.destination_addr":
  794. mNode.DestinationAddr = attr.Value.AsString()
  795. }
  796. }
  797. mNode.MethodName = fmt.Sprintf("%s %s %s:%d%s", "HTTP", method, mNode.Ip, mNode.Port, mNode.Uri)
  798. //mNode.AssumedAppId = Md5ToInt64(descAddr, 16)
  799. }
  800. //func buildMysqlMap(mNode *MapInfoT, sd apmTraceSpan) {
  801. // mNode.Dbn = "unknown"
  802. // mNode.ServiceName = MYSQL_SERVICE_NAME
  803. // mNode.ServiceType = SQL_SERVICE_TYPE
  804. // mNode.MethodName = "database/sql.Query()"
  805. // for _, attr := range sd.Attributes() {
  806. // //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  807. // switch attr.Key {
  808. // case "net.peer.name":
  809. // mNode.Ip = attr.Value.AsString()
  810. // case "net.peer.port":
  811. // mNode.Port = attr.Value.AsInt64()
  812. // case "db.statement":
  813. // query := attr.Value.AsString()
  814. // mNode.Ps = []string{query}
  815. // words := strings.Fields(query)
  816. // if len(words) > 0 {
  817. // mNode.OperType = strings.ToUpper(words[0])
  818. // }
  819. // }
  820. // }
  821. //}
  822. func buildSQLMapEvent(mNode *MapInfoT, event tracesdk.Event) {
  823. mNode.Dbn = "-"
  824. mNode.ServiceName = l7.Protocol(event.ProtocolType).ServiceNameString()
  825. mNode.ServiceType = SQL_SERVICE_TYPE
  826. //mNode.MethodName = "database/sql.Query()"
  827. for _, attr := range event.Attributes {
  828. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  829. switch attr.Key {
  830. case "net.peer.name":
  831. mNode.Ip = attr.Value.AsString()
  832. case "net.peer.port":
  833. mNode.Port = attr.Value.AsInt64()
  834. case "db.statement":
  835. query := attr.Value.AsString()
  836. mNode.MethodName = query
  837. mNode.Ps = []string{query}
  838. words := strings.Fields(query)
  839. if len(words) > 0 {
  840. mNode.OperType = strings.ToUpper(words[0])
  841. }
  842. case "sql.exception":
  843. if attr.Value.AsBool() {
  844. mNode.Exception = 1
  845. } else {
  846. mNode.Exception = 0
  847. }
  848. case "sql.src_addr":
  849. mNode.SrcAddr = attr.Value.AsString()
  850. case "sql.destination_addr":
  851. mNode.DestinationAddr = attr.Value.AsString()
  852. }
  853. }
  854. }
  855. func buildMQMapEvent(mNode *MapInfoT, event tracesdk.Event){
  856. mNode.ServiceName = l7.Protocol(event.ProtocolType).ServiceNameString()
  857. mNode.ServiceType = SQL_SERVICE_TYPE
  858. //mNode.MethodName = "database/sql.Query()"
  859. for _, attr := range event.Attributes {
  860. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  861. switch attr.Key {
  862. case "net.peer.name":
  863. mNode.Ip = attr.Value.AsString()
  864. case "net.peer.port":
  865. mNode.Port = attr.Value.AsInt64()
  866. case "mq.operatype":
  867. mNode.OperType = "produce"
  868. case "mq.uri":
  869. mNode.Uri = attr.Value.AsString()
  870. case "mq.src_addr":
  871. mNode.SrcAddr = attr.Value.AsString()
  872. case "mq.destination_addr":
  873. mNode.DestinationAddr = attr.Value.AsString()
  874. }
  875. }
  876. mNode.Flow = 0
  877. mNode.Schema = ""
  878. }
  879. func buildDNSMapEvent(mNode *MapInfoT, event tracesdk.Event) {
  880. mNode.ServiceName = l7.Protocol(event.ProtocolType).ServiceNameString()
  881. mNode.ServiceType = NET_SERVICE_TYPE
  882. var _type string
  883. var fqdn string
  884. var ips string
  885. var ttl int64
  886. for _, attr := range event.Attributes {
  887. switch attr.Key {
  888. case "dns.type":
  889. _type = attr.Value.AsString()
  890. case "dns.fqdn":
  891. fqdn = attr.Value.AsString()
  892. case "dns.ttl":
  893. ttl = attr.Value.AsInt64()
  894. case "dns.ips":
  895. if attr.Value.AsString() != "" {
  896. ips = "Addr: " + attr.Value.AsString()
  897. }
  898. }
  899. }
  900. mNode.MethodName = fmt.Sprintf("DNS Name: %s Type: %s TTL: %d %s", fqdn, _type, ttl, ips)
  901. }
  902. func buildPostGreSqlMapEvent(mNode *MapInfoT, event tracesdk.Event) {
  903. mNode.Dbn = "-"
  904. mNode.ServiceName = POSTGRESQL_SERVICE_NAME
  905. mNode.ServiceType = SQL_SERVICE_TYPE
  906. //mNode.MethodName = "database/sql.Query()"
  907. for _, attr := range event.Attributes {
  908. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  909. switch attr.Key {
  910. case "net.peer.name":
  911. mNode.Ip = attr.Value.AsString()
  912. case "net.peer.port":
  913. mNode.Port = attr.Value.AsInt64()
  914. case "db.statement":
  915. query := attr.Value.AsString()
  916. mNode.Ps = []string{query}
  917. words := strings.Fields(query)
  918. if len(words) > 0 {
  919. mNode.OperType = strings.ToUpper(words[0])
  920. }
  921. case "sql.exception":
  922. if attr.Value.AsBool() {
  923. mNode.Exception = 1
  924. } else {
  925. mNode.Exception = 0
  926. }
  927. case "sql.src_addr":
  928. mNode.SrcAddr = attr.Value.AsString()
  929. case "sql.destination_addr":
  930. mNode.DestinationAddr = attr.Value.AsString()
  931. }
  932. }
  933. }
  934. func buildMysqlMapEvent(mNode *MapInfoT, event tracesdk.Event) {
  935. mNode.Dbn = "-"
  936. mNode.ServiceName = MYSQL_SERVICE_NAME
  937. mNode.ServiceType = SQL_SERVICE_TYPE
  938. //mNode.MethodName = "database/sql.Query()"
  939. for _, attr := range event.Attributes {
  940. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  941. switch attr.Key {
  942. case "net.peer.name":
  943. mNode.Ip = attr.Value.AsString()
  944. case "net.peer.port":
  945. mNode.Port = attr.Value.AsInt64()
  946. case "db.statement":
  947. query := attr.Value.AsString()
  948. mNode.MethodName = query
  949. mNode.Ps = []string{query}
  950. words := strings.Fields(query)
  951. if len(words) > 0 {
  952. mNode.OperType = strings.ToUpper(words[0])
  953. }
  954. case "sql.exception":
  955. if attr.Value.AsBool() {
  956. mNode.Exception = 1
  957. } else {
  958. mNode.Exception = 0
  959. }
  960. case "sql.src_addr":
  961. mNode.SrcAddr = attr.Value.AsString()
  962. case "sql.destination_addr":
  963. mNode.DestinationAddr = attr.Value.AsString()
  964. }
  965. }
  966. }
  967. func buildDMMapEvent(mNode *MapInfoT, event tracesdk.Event) {
  968. mNode.Dbn = "TEST"
  969. mNode.ServiceName = DM_SERVICE_NAME
  970. mNode.ServiceType = SQL_SERVICE_TYPE
  971. mNode.MethodName = "database/sql.Query()"
  972. for _, attr := range event.Attributes {
  973. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  974. switch attr.Key {
  975. case "net.peer.name":
  976. mNode.Ip = attr.Value.AsString()
  977. case "net.peer.port":
  978. mNode.Port = attr.Value.AsInt64()
  979. case "db.statement":
  980. query := attr.Value.AsString()
  981. mNode.Ps = []string{query}
  982. words := strings.Fields(query)
  983. if len(words) > 0 {
  984. mNode.OperType = strings.ToUpper(words[0])
  985. }
  986. case "sql.exception":
  987. if attr.Value.AsBool() {
  988. mNode.Exception = 1
  989. } else {
  990. mNode.Exception = 0
  991. }
  992. case "sql.src_addr":
  993. mNode.SrcAddr = attr.Value.AsString()
  994. case "sql.destination_addr":
  995. mNode.DestinationAddr = attr.Value.AsString()
  996. }
  997. }
  998. }
  999. func buildRedisMapEvent(mNode *MapInfoT, event tracesdk.Event) {
  1000. mNode.ServiceName = REDIS_SERVICE_NAME
  1001. mNode.ServiceType = NOSQL_SERVICE_TYPE
  1002. //mNode.MethodName = span(sd).Name + " query"
  1003. //mNode.MethodName = "redis.Do()"
  1004. for _, attr := range event.Attributes {
  1005. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  1006. switch attr.Key {
  1007. case "net.peer.name":
  1008. mNode.Ip = attr.Value.AsString()
  1009. case "net.peer.port":
  1010. mNode.Port = attr.Value.AsInt64()
  1011. case "db.statement":
  1012. query := attr.Value.AsString()
  1013. mNode.MethodName = query
  1014. mNode.Ps = []string{query}
  1015. words := strings.Fields(query)
  1016. if len(words) > 0 {
  1017. mNode.OperType = strings.ToUpper(words[0])
  1018. }
  1019. case "nosql.src_addr":
  1020. mNode.SrcAddr = attr.Value.AsString()
  1021. case "nosql.destination_addr":
  1022. mNode.DestinationAddr = attr.Value.AsString()
  1023. }
  1024. }
  1025. }
  1026. func isEnter(_type string) bool {
  1027. if _type == "APPLICATION" {
  1028. return true
  1029. }
  1030. return false
  1031. }
  1032. func span(sd apmTraceSpan) *tracepb.Span {
  1033. if sd == nil {
  1034. return nil
  1035. }
  1036. tid := sd.SpanContext().TraceID()
  1037. sid := sd.SpanContext().SpanID()
  1038. s := &tracepb.Span{
  1039. TraceId: tid[:],
  1040. SpanId: sid[:],
  1041. TraceState: sd.SpanContext().TraceState().String(),
  1042. //Status: status(sd.Status().Code, sd.Status().Description),
  1043. StartTimeUnixNano: uint64(sd.StartTime().UnixNano()),
  1044. EndTimeUnixNano: uint64(sd.EndTime().UnixNano()),
  1045. //Links: links(sd.Links()),
  1046. //Kind: spanKind(sd.SpanKind()),
  1047. Name: sd.Name(),
  1048. Attributes: tracetransform.KeyValues(sd.Attributes()),
  1049. //Events: spanEvents(sd.Events()),
  1050. DroppedAttributesCount: uint32(sd.DroppedAttributes()),
  1051. DroppedEventsCount: uint32(sd.DroppedEvents()),
  1052. DroppedLinksCount: uint32(sd.DroppedLinks()),
  1053. }
  1054. if psid := sd.Parent().SpanID(); psid.IsValid() {
  1055. s.ParentSpanId = psid[:]
  1056. }
  1057. return s
  1058. }
  1059. func Md5ToInt64(strParam string, Len int) int64 {
  1060. sign := md5.Sum([]byte(strParam))
  1061. signStr := fmt.Sprintf("%x", sign)
  1062. charArr := []rune(signStr)
  1063. var intStr string
  1064. for _, value := range charArr {
  1065. intStr += strconv.Itoa(int(value))
  1066. }
  1067. intStr = intStr[:Len]
  1068. int64Data, err := strconv.ParseInt(intStr, 10, 64)
  1069. if err != nil {
  1070. return 0
  1071. }
  1072. return int64Data
  1073. }
  1074. // ns,ms
  1075. func cleanNsTime(time int64) (uint64, uint64) {
  1076. return uint64(time), uint64(math.Round(float64(time) / 1e6))
  1077. }