tools.go 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package opentelemetry
  2. import (
  3. "fmt"
  4. "net/url"
  5. "strconv"
  6. "strings"
  7. "github.com/pkg/errors"
  8. "go.opentelemetry.io/collector/pdata/pcommon"
  9. conventions "go.opentelemetry.io/collector/semconv/v1.18.0"
  10. )
  11. type SpanAttributes struct {
  12. mp pcommon.Map
  13. }
  14. func NewSpanAttributes(attrs map[string]string) SpanAttributes {
  15. mp := pcommon.NewMap()
  16. for key, val := range attrs {
  17. mp.PutStr(key, val)
  18. }
  19. return SpanAttributes{mp}
  20. }
  21. func NewSpanAttributesWithRaw(attrs pcommon.Map) SpanAttributes {
  22. return SpanAttributes{mp: attrs}
  23. }
  24. func (sa SpanAttributes) getAttribute(keys ...string) (val pcommon.Value) {
  25. for _, key := range keys {
  26. if v, ok := sa.mp.Get(key); ok {
  27. return v
  28. }
  29. // log.Debugf("获取span属性%s失败", key)
  30. }
  31. return pcommon.NewValueBytes()
  32. }
  33. func (sa SpanAttributes) HttpRoute() (route string) {
  34. route = sa.getAttribute("http.route", "http.target").AsString()
  35. if route == "" {
  36. rawUrl := sa.HttpUrl()
  37. if urlInfo, err := url.Parse(rawUrl); err == nil {
  38. route = urlInfo.Path
  39. }
  40. }
  41. routes := strings.Split(route, "?")
  42. if len(routes) > 1 {
  43. route = routes[0]
  44. }
  45. return
  46. }
  47. func (sa SpanAttributes) HttpTarget() (target string) {
  48. target = sa.getAttribute("http.target", "http.route").AsString()
  49. if target == "" {
  50. rawUrl := sa.HttpUrl()
  51. if urlInfo, err := url.Parse(rawUrl); err == nil {
  52. if urlInfo.Path != "" && urlInfo.RawQuery != "" {
  53. target = fmt.Sprintf("%s?%s", urlInfo.Path, urlInfo.RawQuery)
  54. } else if urlInfo.Path != "" {
  55. target = urlInfo.Path
  56. }
  57. }
  58. }
  59. return
  60. }
  61. func (sa SpanAttributes) HttpHost() (host string) {
  62. host = sa.getAttribute("http.host").AsString()
  63. if host == "" {
  64. rawUrl := sa.HttpUrl()
  65. if urlInfo, err := url.Parse(rawUrl); err == nil {
  66. host = urlInfo.Host
  67. }
  68. }
  69. return
  70. }
  71. // getHttpUrl 大部分都有http.url,但少部分没有,需要手动拼凑
  72. func (sa SpanAttributes) HttpUrl() (url string) {
  73. url = sa.getAttribute("http.url", "url.full").AsString()
  74. schema := sa.getAttribute("http.schema", "url.scheme").AsString()
  75. if schema == "" {
  76. schema = "http"
  77. }
  78. if url == "" {
  79. host := sa.getAttribute("http.host").AsString()
  80. if host == "" { // 没有host,返回空url
  81. return
  82. }
  83. target := sa.getAttribute("http.target").AsString()
  84. url = fmt.Sprintf("%s://%s%s", schema, host, target)
  85. } else {
  86. if strings.HasPrefix(url, "http://") || strings.HasPrefix(url, "https://") {
  87. return
  88. }
  89. if strings.HasPrefix(url, "/") { // 有sdk生成的http.url仅包抱一个类似于/path的结构,对于该种结构,对于这种结构,直接返回
  90. return
  91. }
  92. url = schema + "://" + url // 之所以加一个http://前缀,是因为url.Parse时,如果没有http://前缀时,不能正常解析
  93. }
  94. return
  95. }
  96. func (sa SpanAttributes) StatusCode() int64 {
  97. code := sa.getAttribute("http.status_code", "http.response.status_code").AsString()
  98. statusCode, err := strconv.ParseInt(code, 10, 64)
  99. if err != nil {
  100. return -1
  101. }
  102. return statusCode
  103. }
  104. func (sa SpanAttributes) HttpFlavor() string {
  105. flavor := sa.getAttribute("http.flavor", "http.protocol").AsString()
  106. if arr := strings.Split(flavor, "/"); len(arr) > 1 {
  107. return arr[1]
  108. }
  109. return flavor
  110. }
  111. func (sa SpanAttributes) HttpMethod() string {
  112. // http.request.method为新版本定义
  113. // http.method为旧版本定义
  114. return sa.getAttribute("http.request.method", "http.method").AsString()
  115. }
  116. func (sa SpanAttributes) UserAgent() string {
  117. return sa.getAttribute("http.user_agent", "user_agent.original").AsString()
  118. }
  119. func (sa SpanAttributes) DbSystem() string {
  120. return sa.getAttribute("db.system").AsString()
  121. }
  122. func (sa SpanAttributes) IsDB() bool {
  123. return sa.getAttribute("db.system", "db.type", "db.operate").AsString() != ""
  124. }
  125. // 获取数据库服务的地址
  126. func (sa SpanAttributes) DbServerAddress() string {
  127. return sa.getAttribute("server.address", "network.peer.address", "net.peer.name").AsString()
  128. }
  129. // 获取数据库服务的端口
  130. func (sa SpanAttributes) DbServerPort() string {
  131. return sa.getAttribute("server.port", "network.peer.port", "net.peer.port").AsString()
  132. }
  133. func (sa SpanAttributes) NetworkPeerAddress() string {
  134. // server.address代表真实的服务的地址,即使中间有代理,这个值也是真实服务的值,大根率没有
  135. // 后面两个都代表直接通信的地址,可能是代理,第一个为目前官方定义的,第二个是之前版本定义的
  136. return sa.getAttribute("server.address", "network.peer.address", "net.peer.name").AsString()
  137. }
  138. func (sa SpanAttributes) NetworkPeerPort() string {
  139. // 参考NetwordPeerAddress说明
  140. return sa.getAttribute("server.port", "network.peer.port", "net.peer.port").AsString()
  141. }
  142. func (sa SpanAttributes) RpcSystem() string {
  143. return sa.getAttribute("rpc.system").AsString()
  144. }
  145. func (sa SpanAttributes) WrapSpanName(spanName, spanKind string) string {
  146. newSpanName := spanName
  147. if spanKind == "SPAN_KIND_CLIENT" {
  148. route := sa.HttpRoute()
  149. if route != "" {
  150. newSpanName = fmt.Sprintf("%s -> %s", spanName, route)
  151. }
  152. }
  153. return newSpanName
  154. }
  155. // 返回请求方法和spanName
  156. func (sa SpanAttributes) UnWrapSpanName(spanName string) (string, string, error) {
  157. if strings.Contains(spanName, " -> ") {
  158. arr := strings.Split(spanName, " -> ")
  159. method, route := arr[0], arr[1]
  160. if strings.HasPrefix(method, "HTTP ") {
  161. httpMethod := strings.Split(method, " ")
  162. method = httpMethod[1]
  163. }
  164. return method, route, nil
  165. }
  166. return "", "", fmt.Errorf("span name: %s 未包装过", spanName)
  167. }
  168. // 消息系统 ------------- start ---------------
  169. func (sa SpanAttributes) MessagingSystem() string {
  170. return sa.getAttribute("messaging.system").AsString()
  171. }
  172. func (sa SpanAttributes) MessagingOperation() string {
  173. return sa.getAttribute("messaging.operation").AsString()
  174. }
  175. func (sa SpanAttributes) MessagingServerAddress() string {
  176. return sa.getAttribute("server.address", "network.peer.address", "net.peer.name").AsString()
  177. }
  178. // 消息系统 ------------- end ---------------
  179. type ResourceAttributes struct {
  180. res *pcommon.Resource
  181. }
  182. func NewResourceAttributes(res *pcommon.Resource) ResourceAttributes {
  183. return ResourceAttributes{res}
  184. }
  185. // 获取app name,虽然这里叫app name,但其实是app alias
  186. func (ra *ResourceAttributes) AppName() (string, error) {
  187. res := ra.res
  188. // 在collector未使用res app.name作为AppAlias时, 暂时注释
  189. // if appName, ok := res.Attributes().Get("app.name"); ok { // 优先使用 resource attributes中的 app.name参数判断
  190. // return appName.AsString(), nil
  191. // }
  192. var err error
  193. appAlias := ""
  194. if command, ok := res.Attributes().Get(conventions.AttributeProcessCommandLine); ok {
  195. cmds := strings.Split(command.AsString(), " ")
  196. for _, cmd := range cmds {
  197. if strings.HasPrefix(cmd, "-DAPP_NAME") { // 仅针对java
  198. arr := strings.Split(cmd, "=")
  199. if len(arr) == 2 {
  200. appAlias = arr[1]
  201. } else {
  202. err = fmt.Errorf("-DAPP_NAME参数非法:%s", cmd)
  203. }
  204. break
  205. }
  206. }
  207. }
  208. if appAlias == "" {
  209. if appName, ok := res.Attributes().Get("service.namespace"); ok {
  210. appAlias = appName.AsString()
  211. } else if appName, ok := res.Attributes().Get("app.name"); ok {
  212. appAlias = appName.AsString()
  213. } else {
  214. appAlias = "UNSET"
  215. err = errors.New("未设置service.namespace或app.name")
  216. }
  217. }
  218. return appAlias, err
  219. }
  220. // 获取service name
  221. func (ra *ResourceAttributes) ServiceName() (string, error) {
  222. var serviceName string
  223. var err error
  224. if v, ok := ra.res.Attributes().Get(conventions.AttributeServiceName); ok {
  225. serviceName = v.Str()
  226. } else {
  227. err = errors.New("未获取到service name")
  228. }
  229. return serviceName, err
  230. }