apm_exporter.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. package otlptrace
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "fmt"
  6. "sort"
  7. "strconv"
  8. "strings"
  9. "sync"
  10. "time"
  11. "go.opentelemetry.io/otel/exporters/otlp/otlptrace/internal/tracetransform"
  12. tracesdk "go.opentelemetry.io/otel/sdk/trace"
  13. tracepb "go.opentelemetry.io/proto/otlp/trace/v1"
  14. )
  15. const (
  16. APP_SERVICE_TYPE = "APPLICATION"
  17. SQL_SERVICE_TYPE = "SQL"
  18. NOSQL_SERVICE_TYPE = "NOSQL"
  19. HTTP_SERVICE_TYPE = "HTTP"
  20. )
  21. const (
  22. GO_SERVICE_NAME = "GO"
  23. MYSQL_SERVICE_NAME = "MYSQL"
  24. REDIS_SERVICE_NAME = "REDIS"
  25. HTTP_SERVICE_NAME = "HTTPCLIENT"
  26. )
  27. type apmTraceSpan tracesdk.ReadOnlySpan
  28. // GO:0:10154813500555812:5450531005555981:5610250100539899:ee022542c3940f1b:1001025098564810:888ceb3df1bdbe2c:110
  29. type RootDataT struct {
  30. AccountId int `json:"account_id"`
  31. AgentId int64 `json:"agent_id"`
  32. AgentVersion string `json:"agent_version"`
  33. AppId int64 `json:"app_id"`
  34. AppIdFrom int64 `json:"app_id_from"` // from header app_id
  35. AppName string `json:"app_name"`
  36. CalledId int64 `json:"called_id"` // from header assumed_app_id
  37. ClientIp string `json:"client_ip"`
  38. CollTime uint64 `json:"coll_time"`
  39. Cpu int `json:"cpu"`
  40. Custom string `json:"custom"`
  41. HostId int64 `json:"host_id"`
  42. HostName string `json:"host_name"`
  43. HttpCode int64 `json:"http_code"`
  44. HttpMethod string `json:"http_method"`
  45. InstanceId int64 `json:"instance_id"`
  46. InstanceIdFrom int64 `json:"instance_id_from"` // from header instance_id
  47. LocalPort int64 `json:"local_port"`
  48. Maps []MapInfoT `json:"maps"`
  49. MemU int `json:"mem_u"`
  50. MemUP int `json:"mem_u_p"`
  51. OperType string `json:"oper_type"`
  52. Parameters []interface{} `json:"parameters"`
  53. ParentTaskName int `json:"parent_task_name"`
  54. Period int `json:"period"`
  55. RespTime uint64 `json:"resp_time"`
  56. Sampling int `json:"sampling"`
  57. ServiceName string `json:"service_name"`
  58. ServiceType string `json:"service_type"`
  59. Sip string `json:"sip"`
  60. Sn string `json:"sn"`
  61. SpanIdFrom string `json:"span_id_from"` // from header span_id
  62. Sport int64 `json:"sport"`
  63. TId int `json:"t_id"`
  64. TName string `json:"t_name"`
  65. TraceId string `json:"trace_id"` // from header trace_id
  66. TransIds []interface{} `json:"trans_ids"`
  67. TypeFrom string `json:"type_from"`
  68. Uri string `json:"uri"`
  69. UserDir int `json:"user_dir"`
  70. VipIds []interface{} `json:"vip_ids"`
  71. }
  72. type MapInfoT struct {
  73. Dbn string `json:"dbn,omitempty"`
  74. Exception int `json:"exception,omitempty"`
  75. ExceptionMsg string `json:"exception_msg,omitempty"`
  76. ExceptionStack string `json:"exception_stack,omitempty"`
  77. Ip string `json:"ip,omitempty"`
  78. Level int `json:"level"`
  79. MethodDesc string `json:"method_desc,omitempty"`
  80. MethodName string `json:"method_name"`
  81. Nid int `json:"nid"`
  82. OperType string `json:"oper_type,omitempty"`
  83. Pid int `json:"pid"`
  84. Port int64 `json:"port,omitempty"`
  85. Ps []string `json:"ps,omitempty"`
  86. PureTime uint64 `json:"pure_time"`
  87. ServiceName string `json:"service_name"`
  88. ServiceType string `json:"service_type"`
  89. StartTime uint64 `json:"start_time"`
  90. EndTime uint64 `json:"end_time"`
  91. WallTime uint64 `json:"wall_time"`
  92. Schema string `json:"schema,omitempty"`
  93. AssumedAppId int64 `json:"assumed_app_id,omitempty"`
  94. Uri string `json:"uri,omitempty"`
  95. SpanId string `json:"span_id,omitempty"`
  96. }
  97. type TraceMapT struct {
  98. RootData RootDataT
  99. Index int
  100. lock *sync.RWMutex
  101. TheEnd bool
  102. }
  103. var TraceRootMap map[string]*TraceMapT
  104. func init() {
  105. TraceRootMap = make(map[string]*TraceMapT)
  106. go func() {
  107. for {
  108. //fmt.Println(G_sdl)
  109. time.Sleep(5 * time.Second)
  110. }
  111. }()
  112. }
  113. var G_sdl int
  114. func tracetransformData(sdl []tracesdk.ReadOnlySpan) []RootDataT {
  115. G_sdl += len(sdl)
  116. if len(sdl) == 0 {
  117. return nil
  118. }
  119. for _, sd := range sdl {
  120. if sd == nil {
  121. continue
  122. }
  123. traceId := sd.SpanContext().TraceID().String()
  124. if _, ok := TraceRootMap[traceId]; !ok {
  125. TraceRootMap[traceId] = &TraceMapT{RootData: initRootData(traceId), Index: 1}
  126. }
  127. TraceRootMap[traceId].Index++
  128. buildAndAssemblyMap(sd, TraceRootMap[traceId])
  129. }
  130. // 发送完整数据 | 大量长耗时请求会增加内存占用
  131. sendData := []RootDataT{}
  132. for traceId, v := range TraceRootMap {
  133. if v.TheEnd {
  134. buildLevel(v)
  135. sendData = append(sendData, v.RootData)
  136. delete(TraceRootMap, traceId)
  137. //fmt.Println("the end!")
  138. } else {
  139. //fmt.Println("not end!")
  140. }
  141. }
  142. // Transform the categorized map into a slice
  143. aa, err := json.Marshal(sendData)
  144. fmt.Println(err)
  145. fmt.Println(string(aa))
  146. fmt.Println(len(sendData))
  147. fmt.Println(len(sdl))
  148. return sendData
  149. }
  150. type TimeMap struct {
  151. Time uint64
  152. Type int
  153. Map *MapInfoT
  154. }
  155. func buildLevel(sdl *TraceMapT) {
  156. nidMap := make(map[int]*MapInfoT)
  157. mapSlice := []TimeMap{}
  158. for i, v := range sdl.RootData.Maps {
  159. if v.ServiceType == "APPLICATION" {
  160. continue
  161. }
  162. nidMap[v.Nid] = &sdl.RootData.Maps[i]
  163. timeStartMap := TimeMap{
  164. Time: v.StartTime,
  165. Type: 0,
  166. Map: &sdl.RootData.Maps[i],
  167. }
  168. mapSlice = append(mapSlice, timeStartMap)
  169. timeEndMap := TimeMap{
  170. Time: v.EndTime,
  171. Type: 1,
  172. Map: &sdl.RootData.Maps[i],
  173. }
  174. mapSlice = append(mapSlice, timeEndMap)
  175. }
  176. sort.Slice(mapSlice, func(i, j int) bool {
  177. return mapSlice[i].Time < mapSlice[j].Time
  178. })
  179. funStack := []TimeMap{}
  180. currentNid := 1
  181. Nid := 2
  182. level := 2
  183. for _, v := range mapSlice {
  184. // fmt.Println("SliceSliceindex", k, "value", v.Time, v.Type, v.Map.MethodName, v.Map.Nid)
  185. if v.Type == 0 {
  186. // 函数入口
  187. funStack = append(funStack, v)
  188. v.Map.Pid = currentNid
  189. v.Map.Level = level
  190. v.Map.Nid = Nid
  191. currentNid = Nid
  192. level += 1
  193. Nid += 1
  194. } else if v.Type == 1 {
  195. // 函数出口
  196. len := len(funStack)
  197. funStack = funStack[:len-1]
  198. if (len - 2) < 0 {
  199. currentNid = 1
  200. } else {
  201. currentNid = funStack[len-2].Map.Nid
  202. }
  203. level -= 1
  204. }
  205. }
  206. }
  207. func initRootData(traceId string) RootDataT {
  208. data := RootDataT{
  209. AccountId: 110,
  210. AgentId: 1011005252979954, // TODO 更新 基于 ip:port + process_name + exe路径生成
  211. AgentVersion: "2.1.0",
  212. AppId: 5410049101545798, // TODO 更新 基于appname生成
  213. AppIdFrom: -1,
  214. AppName: "eBPF-agent", // TODO 更新 ip:port || process_name
  215. CalledId: -1,
  216. ClientIp: "",
  217. CollTime: 0,
  218. Cpu: 0,
  219. Custom: "",
  220. HostId: 10154813500555812,
  221. HostName: "localhost",
  222. HttpCode: 0,
  223. HttpMethod: "",
  224. InstanceId: 1005051101515357, // TODO 更新 基于ip:port
  225. InstanceIdFrom: -1,
  226. Maps: []MapInfoT{},
  227. MemU: 0,
  228. MemUP: 0,
  229. OperType: "",
  230. Parameters: []interface{}{},
  231. ParentTaskName: 0,
  232. Period: -1,
  233. RespTime: 0,
  234. Sampling: 0,
  235. ServiceName: "GO",
  236. ServiceType: APP_SERVICE_TYPE,
  237. Sip: "",
  238. Sn: "",
  239. SpanIdFrom: "",
  240. Sport: 0,
  241. TId: -1,
  242. TName: "",
  243. TraceId: traceId,
  244. TransIds: []interface{}{},
  245. TypeFrom: "",
  246. Uri: "",
  247. UserDir: 0,
  248. VipIds: []interface{}{},
  249. }
  250. return data
  251. }
  252. func initMapNode(spanSd *tracepb.Span) (MapInfoT, string) {
  253. mNode := MapInfoT{
  254. Exception: 0,
  255. ExceptionMsg: "",
  256. ExceptionStack: "",
  257. Ip: "",
  258. Level: 2,
  259. Pid: 1,
  260. Port: 0,
  261. Ps: []string{},
  262. ServiceName: "",
  263. ServiceType: "",
  264. WallTime: 0,
  265. }
  266. mNode.MethodName = spanSd.Name
  267. mNode.PureTime = (spanSd.EndTimeUnixNano - spanSd.StartTimeUnixNano) / 1e3
  268. mNode.WallTime = mNode.PureTime
  269. mNode.StartTime = spanSd.StartTimeUnixNano
  270. mNode.EndTime = spanSd.EndTimeUnixNano
  271. for _, attr := range spanSd.GetAttributes() {
  272. switch attr.Key {
  273. case "nid":
  274. mNode.Nid = int(attr.Value.GetIntValue())
  275. case "pid":
  276. mNode.Pid = int(attr.Value.GetIntValue())
  277. case "level":
  278. mNode.Level = int(attr.Value.GetIntValue())
  279. }
  280. }
  281. return mNode, spanSd.Name
  282. }
  283. // 构建拼装
  284. func buildAndAssemblyMap(sd apmTraceSpan, traceRoot *TraceMapT) MapInfoT {
  285. mNode, mapType := initMapNode(span(sd))
  286. switch mapType {
  287. case "APPLICATION":
  288. buildAppMap(&mNode, traceRoot, sd)
  289. traceRoot.TheEnd = true
  290. case "HTTP":
  291. buildHttpMap(&mNode, sd)
  292. case "Mysql":
  293. buildMysqlMap(&mNode, sd)
  294. case "Redis":
  295. buildRedisMap(&mNode, sd)
  296. }
  297. if mapType != "" {
  298. mNode.Nid = traceRoot.Index
  299. traceRoot.RootData.Maps = append(traceRoot.RootData.Maps, mNode)
  300. }
  301. return mNode
  302. }
  303. func buildAppMap(mNode *MapInfoT, traceRoot *TraceMapT, sd apmTraceSpan) {
  304. mNode.ServiceName = GO_SERVICE_NAME
  305. mNode.ServiceType = APP_SERVICE_TYPE
  306. mNode.MethodName = "net/http.(*Transport).roundTrip()"
  307. mNode.Level = 1
  308. mNode.Pid = 0
  309. mNode.Nid = 1
  310. // 构建root节点
  311. traceRoot.RootData.RespTime = mNode.PureTime
  312. traceRoot.RootData.CollTime = mNode.StartTime
  313. traceRoot.Index = 1
  314. for _, attr := range sd.Attributes() {
  315. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  316. switch attr.Key {
  317. case "http.uri":
  318. traceRoot.RootData.Uri = attr.Value.AsString()
  319. case "http.method":
  320. traceRoot.RootData.HttpMethod = attr.Value.AsString()
  321. case "http.status_code":
  322. traceRoot.RootData.HttpCode = attr.Value.AsInt64()
  323. case "net.peer.name":
  324. traceRoot.RootData.ClientIp = attr.Value.AsString()
  325. traceRoot.RootData.Sip = attr.Value.AsString()
  326. traceRoot.RootData.Sn = attr.Value.AsString()
  327. case "net.peer.port":
  328. traceRoot.RootData.Sport = attr.Value.AsInt64()
  329. traceRoot.RootData.LocalPort = attr.Value.AsInt64()
  330. case "server.trace_id_from":
  331. traceRoot.RootData.TraceId = attr.Value.AsString()
  332. case "server.called_id":
  333. traceRoot.RootData.CalledId = attr.Value.AsInt64()
  334. case "server.instance_id_from":
  335. traceRoot.RootData.InstanceIdFrom = attr.Value.AsInt64()
  336. case "server.app_id_from":
  337. traceRoot.RootData.AppIdFrom = attr.Value.AsInt64()
  338. case "server.span_id_from":
  339. traceRoot.RootData.SpanIdFrom = attr.Value.AsString()
  340. case "server.type_from":
  341. traceRoot.RootData.TypeFrom = attr.Value.AsString()
  342. }
  343. }
  344. }
  345. func buildHttpMap(mNode *MapInfoT, sd apmTraceSpan) {
  346. mNode.ServiceName = HTTP_SERVICE_NAME
  347. mNode.ServiceType = HTTP_SERVICE_TYPE
  348. mNode.Schema = "http"
  349. mNode.MethodName = "net/http.serverHandler.ServeHTTP()"
  350. var descAddr string
  351. for _, attr := range sd.Attributes() {
  352. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  353. switch attr.Key {
  354. case "http.ip":
  355. mNode.Ip = attr.Value.AsString()
  356. descAddr += mNode.Ip
  357. case "http.port":
  358. mNode.Port = attr.Value.AsInt64()
  359. descAddr += ":" + attr.Value.AsString()
  360. case "http.uri":
  361. mNode.Uri = attr.Value.AsString()
  362. case "http.assumed_app_id":
  363. mNode.AssumedAppId = attr.Value.AsInt64()
  364. case "http.span_id":
  365. mNode.SpanId = attr.Value.AsString()
  366. }
  367. }
  368. //mNode.AssumedAppId = Md5ToInt64(descAddr, 16)
  369. }
  370. func buildMysqlMap(mNode *MapInfoT, sd apmTraceSpan) {
  371. mNode.Dbn = "unknown"
  372. mNode.ServiceName = MYSQL_SERVICE_NAME
  373. mNode.ServiceType = SQL_SERVICE_TYPE
  374. mNode.MethodName = "database/sql.Query()"
  375. for _, attr := range sd.Attributes() {
  376. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  377. switch attr.Key {
  378. case "net.peer.name":
  379. mNode.Ip = attr.Value.AsString()
  380. case "net.peer.port":
  381. mNode.Port = attr.Value.AsInt64()
  382. case "db.statement":
  383. query := attr.Value.AsString()
  384. mNode.Ps = []string{query}
  385. words := strings.Fields(query)
  386. if len(words) > 0 {
  387. mNode.OperType = strings.ToUpper(words[0])
  388. }
  389. }
  390. }
  391. }
  392. func buildRedisMap(mNode *MapInfoT, sd apmTraceSpan) {
  393. mNode.ServiceName = REDIS_SERVICE_NAME
  394. mNode.ServiceType = NOSQL_SERVICE_TYPE
  395. //mNode.MethodName = span(sd).Name + " query"
  396. mNode.MethodName = "redis.Do()"
  397. for _, attr := range sd.Attributes() {
  398. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  399. switch attr.Key {
  400. case "net.peer.name":
  401. mNode.Ip = attr.Value.AsString()
  402. case "net.peer.port":
  403. mNode.Port = attr.Value.AsInt64()
  404. case "db.statement":
  405. query := attr.Value.AsString()
  406. mNode.Ps = []string{query}
  407. words := strings.Fields(query)
  408. if len(words) > 0 {
  409. mNode.OperType = strings.ToUpper(words[0])
  410. }
  411. }
  412. }
  413. }
  414. func isEnter(_type string) bool {
  415. if _type == "APPLICATION" {
  416. return true
  417. }
  418. return false
  419. }
  420. func span(sd apmTraceSpan) *tracepb.Span {
  421. if sd == nil {
  422. return nil
  423. }
  424. tid := sd.SpanContext().TraceID()
  425. sid := sd.SpanContext().SpanID()
  426. s := &tracepb.Span{
  427. TraceId: tid[:],
  428. SpanId: sid[:],
  429. TraceState: sd.SpanContext().TraceState().String(),
  430. //Status: status(sd.Status().Code, sd.Status().Description),
  431. StartTimeUnixNano: uint64(sd.StartTime().UnixNano()),
  432. EndTimeUnixNano: uint64(sd.EndTime().UnixNano()),
  433. //Links: links(sd.Links()),
  434. //Kind: spanKind(sd.SpanKind()),
  435. Name: sd.Name(),
  436. Attributes: tracetransform.KeyValues(sd.Attributes()),
  437. //Events: spanEvents(sd.Events()),
  438. DroppedAttributesCount: uint32(sd.DroppedAttributes()),
  439. DroppedEventsCount: uint32(sd.DroppedEvents()),
  440. DroppedLinksCount: uint32(sd.DroppedLinks()),
  441. }
  442. if psid := sd.Parent().SpanID(); psid.IsValid() {
  443. s.ParentSpanId = psid[:]
  444. }
  445. return s
  446. }
  447. func Md5ToInt64(strParam string, Len int) int64 {
  448. sign := md5.Sum([]byte(strParam))
  449. signStr := fmt.Sprintf("%x", sign)
  450. charArr := []rune(signStr)
  451. var intStr string
  452. for _, value := range charArr {
  453. intStr += strconv.Itoa(int(value))
  454. }
  455. intStr = intStr[:Len]
  456. int64Data, err := strconv.ParseInt(intStr, 10, 64)
  457. if err != nil {
  458. return 0
  459. }
  460. return int64Data
  461. }