apm_exporter.go 12 KB

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