apm_exporter.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. fmt.Println("len sdl", len(sdl))
  106. if len(sdl) == 0 {
  107. return nil
  108. }
  109. for _, sd := range sdl {
  110. if sd == nil {
  111. continue
  112. }
  113. traceId := sd.SpanContext().TraceID().String()
  114. if _, ok := TraceRootMap[traceId]; !ok {
  115. TraceRootMap[traceId] = &TraceMapT{RootData: initRootData(traceId), Index: 1}
  116. }
  117. TraceRootMap[traceId].Index++
  118. buildAndAssemblyMap(sd, TraceRootMap[traceId])
  119. }
  120. // 发送完整数据 | 大量长耗时请求会增加内存占用
  121. sendData := []RootDataT{}
  122. for traceId, v := range TraceRootMap {
  123. if v.TheEnd {
  124. sendData = append(sendData, v.RootData)
  125. delete(TraceRootMap, traceId)
  126. fmt.Println("the end!")
  127. } else {
  128. fmt.Println("not end!")
  129. }
  130. }
  131. // Transform the categorized map into a slice
  132. aa, err := json.Marshal(sendData)
  133. fmt.Println(err)
  134. fmt.Println(string(aa))
  135. fmt.Println(len(sendData))
  136. fmt.Println(len(sdl))
  137. return sendData
  138. }
  139. func initRootData(traceId string) RootDataT {
  140. data := RootDataT{
  141. AccountId: 110,
  142. AgentId: 1011005252979954, // TODO 更新 基于 ip:port + process_name + exe路径生成
  143. AgentVersion: "2.1.0",
  144. AppId: 5410049101545798, // TODO 更新 基于appname生成
  145. AppIdFrom: -1,
  146. AppName: "eBPF-agent", // TODO 更新 ip:port || process_name
  147. CalledId: -1,
  148. ClientIp: "",
  149. CollTime: 0,
  150. Cpu: 0,
  151. Custom: "",
  152. HostId: 10154813500555812,
  153. HostName: "localhost",
  154. HttpCode: 0,
  155. HttpMethod: "",
  156. InstanceId: 1005051101515357, // TODO 更新 基于ip:port
  157. InstanceIdFrom: -1,
  158. Maps: []MapInfoT{},
  159. MemU: 0,
  160. MemUP: 0,
  161. OperType: "",
  162. Parameters: []interface{}{},
  163. ParentTaskName: 0,
  164. Period: -1,
  165. RespTime: 0,
  166. Sampling: 0,
  167. ServiceName: "GO",
  168. ServiceType: APP_SERVICE_TYPE,
  169. Sip: "",
  170. Sn: "",
  171. SpanIdFrom: "",
  172. Sport: 0,
  173. TId: -1,
  174. TName: "",
  175. TraceId: traceId,
  176. TransIds: []interface{}{},
  177. TypeFrom: "",
  178. Uri: "",
  179. UserDir: 0,
  180. VipIds: []interface{}{},
  181. }
  182. return data
  183. }
  184. func initMapNode(spanSd *tracepb.Span) (MapInfoT, string) {
  185. mNode := MapInfoT{
  186. Exception: 0,
  187. ExceptionMsg: "",
  188. ExceptionStack: "",
  189. Ip: "",
  190. Level: 2,
  191. Pid: 1,
  192. Port: 0,
  193. Ps: []string{},
  194. ServiceName: "",
  195. ServiceType: "",
  196. WallTime: 0,
  197. }
  198. mNode.PureTime = (spanSd.EndTimeUnixNano - spanSd.StartTimeUnixNano) / 1e3
  199. mNode.WallTime = mNode.PureTime
  200. mNode.StartTime = spanSd.StartTimeUnixNano / 1e6
  201. return mNode, spanSd.Name
  202. }
  203. // 构建拼装
  204. func buildAndAssemblyMap(sd apmTraceSpan, traceRoot *TraceMapT) MapInfoT {
  205. mNode, mapType := initMapNode(span(sd))
  206. switch mapType {
  207. case "APPLICATION":
  208. buildAppMap(&mNode, traceRoot, sd)
  209. traceRoot.TheEnd = true
  210. case "HTTP":
  211. buildHttpMap(&mNode, sd)
  212. case "Mysql":
  213. buildMysqlMap(&mNode, sd)
  214. case "Redis":
  215. buildRedisMap(&mNode, sd)
  216. }
  217. if mapType != "" {
  218. mNode.Nid = traceRoot.Index
  219. traceRoot.RootData.Maps = append(traceRoot.RootData.Maps, mNode)
  220. }
  221. return mNode
  222. }
  223. func buildAppMap(mNode *MapInfoT, traceRoot *TraceMapT, sd apmTraceSpan) {
  224. mNode.ServiceName = GO_SERVICE_NAME
  225. mNode.ServiceType = APP_SERVICE_TYPE
  226. mNode.MethodName = "net/http.(*Transport).roundTrip()"
  227. mNode.Level = 1
  228. mNode.Pid = 0
  229. // 构建root节点
  230. traceRoot.RootData.RespTime = mNode.PureTime
  231. traceRoot.RootData.CollTime = mNode.StartTime
  232. traceRoot.Index = 1
  233. for _, attr := range sd.Attributes() {
  234. fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  235. switch attr.Key {
  236. case "http.uri":
  237. traceRoot.RootData.Uri = attr.Value.AsString()
  238. case "http.method":
  239. traceRoot.RootData.HttpMethod = attr.Value.AsString()
  240. case "http.status_code":
  241. traceRoot.RootData.HttpCode = attr.Value.AsInt64()
  242. case "net.peer.name":
  243. traceRoot.RootData.ClientIp = attr.Value.AsString()
  244. traceRoot.RootData.Sip = attr.Value.AsString()
  245. traceRoot.RootData.Sn = attr.Value.AsString()
  246. case "net.peer.port":
  247. traceRoot.RootData.Sport = attr.Value.AsInt64()
  248. traceRoot.RootData.LocalPort = attr.Value.AsInt64()
  249. case "server.trace_id_from":
  250. traceRoot.RootData.TraceId = attr.Value.AsString()
  251. case "server.called_id":
  252. traceRoot.RootData.CalledId = attr.Value.AsInt64()
  253. case "server.instance_id_from":
  254. traceRoot.RootData.InstanceIdFrom = attr.Value.AsInt64()
  255. case "server.app_id_from":
  256. traceRoot.RootData.AppIdFrom = attr.Value.AsInt64()
  257. case "server.span_id_from":
  258. traceRoot.RootData.SpanIdFrom = attr.Value.AsString()
  259. }
  260. }
  261. }
  262. func buildHttpMap(mNode *MapInfoT, sd apmTraceSpan) {
  263. mNode.ServiceName = HTTP_SERVICE_NAME
  264. mNode.ServiceType = HTTP_SERVICE_TYPE
  265. mNode.Schema = "http"
  266. mNode.MethodName = "net/http.serverHandler.ServeHTTP()"
  267. var descAddr string
  268. for _, attr := range sd.Attributes() {
  269. fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  270. switch attr.Key {
  271. case "http.ip":
  272. mNode.Ip = attr.Value.AsString()
  273. descAddr += mNode.Ip
  274. case "http.port":
  275. mNode.Port = attr.Value.AsInt64()
  276. descAddr += ":" + attr.Value.AsString()
  277. case "http.uri":
  278. mNode.Uri = attr.Value.AsString()
  279. case "http.assumed_app_id":
  280. mNode.AssumedAppId = attr.Value.AsInt64()
  281. case "http.span_id":
  282. mNode.SpanId = attr.Value.AsString()
  283. }
  284. }
  285. //mNode.AssumedAppId = Md5ToInt64(descAddr, 16)
  286. }
  287. func buildMysqlMap(mNode *MapInfoT, sd apmTraceSpan) {
  288. mNode.Dbn = "unknown"
  289. mNode.ServiceName = MYSQL_SERVICE_NAME
  290. mNode.ServiceType = SQL_SERVICE_TYPE
  291. mNode.MethodName = "database/sql.Query()"
  292. for _, attr := range sd.Attributes() {
  293. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  294. switch attr.Key {
  295. case "net.peer.name":
  296. mNode.Ip = attr.Value.AsString()
  297. case "net.peer.port":
  298. mNode.Port = attr.Value.AsInt64()
  299. case "db.statement":
  300. query := attr.Value.AsString()
  301. mNode.Ps = []string{query}
  302. words := strings.Fields(query)
  303. if len(words) > 0 {
  304. mNode.OperType = strings.ToUpper(words[0])
  305. }
  306. }
  307. }
  308. }
  309. func buildRedisMap(mNode *MapInfoT, sd apmTraceSpan) {
  310. mNode.ServiceName = REDIS_SERVICE_NAME
  311. mNode.ServiceType = NOSQL_SERVICE_TYPE
  312. //mNode.MethodName = span(sd).Name + " query"
  313. mNode.MethodName = "redis.Do()"
  314. for _, attr := range sd.Attributes() {
  315. //fmt.Println(attr.Key, ":", attr.Value.AsInterface())
  316. switch attr.Key {
  317. case "net.peer.name":
  318. mNode.Ip = attr.Value.AsString()
  319. case "net.peer.port":
  320. mNode.Port = attr.Value.AsInt64()
  321. case "db.statement":
  322. query := attr.Value.AsString()
  323. mNode.Ps = []string{query}
  324. words := strings.Fields(query)
  325. if len(words) > 0 {
  326. mNode.OperType = strings.ToUpper(words[0])
  327. }
  328. }
  329. }
  330. }
  331. func isEnter(_type string) bool {
  332. if _type == "APPLICATION" {
  333. return true
  334. }
  335. return false
  336. }
  337. func span(sd apmTraceSpan) *tracepb.Span {
  338. if sd == nil {
  339. return nil
  340. }
  341. tid := sd.SpanContext().TraceID()
  342. sid := sd.SpanContext().SpanID()
  343. s := &tracepb.Span{
  344. TraceId: tid[:],
  345. SpanId: sid[:],
  346. TraceState: sd.SpanContext().TraceState().String(),
  347. //Status: status(sd.Status().Code, sd.Status().Description),
  348. StartTimeUnixNano: uint64(sd.StartTime().UnixNano()),
  349. EndTimeUnixNano: uint64(sd.EndTime().UnixNano()),
  350. //Links: links(sd.Links()),
  351. //Kind: spanKind(sd.SpanKind()),
  352. Name: sd.Name(),
  353. Attributes: tracetransform.KeyValues(sd.Attributes()),
  354. //Events: spanEvents(sd.Events()),
  355. DroppedAttributesCount: uint32(sd.DroppedAttributes()),
  356. DroppedEventsCount: uint32(sd.DroppedEvents()),
  357. DroppedLinksCount: uint32(sd.DroppedLinks()),
  358. }
  359. if psid := sd.Parent().SpanID(); psid.IsValid() {
  360. s.ParentSpanId = psid[:]
  361. }
  362. return s
  363. }
  364. func Md5ToInt64(strParam string, Len int) int64 {
  365. sign := md5.Sum([]byte(strParam))
  366. signStr := fmt.Sprintf("%x", sign)
  367. charArr := []rune(signStr)
  368. var intStr string
  369. for _, value := range charArr {
  370. intStr += strconv.Itoa(int(value))
  371. }
  372. intStr = intStr[:Len]
  373. int64Data, err := strconv.ParseInt(intStr, 10, 64)
  374. if err != nil {
  375. return 0
  376. }
  377. return int64Data
  378. }