apm_exporter.go 11 KB

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