utils.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package trace
  2. import (
  3. "context"
  4. "net"
  5. "strings"
  6. ztrace "github.com/zeromicro/go-zero/internal/trace"
  7. "go.opentelemetry.io/otel/attribute"
  8. semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
  9. "google.golang.org/grpc/peer"
  10. )
  11. const localhost = "127.0.0.1"
  12. var (
  13. // SpanIDFromContext returns the span id from ctx.
  14. SpanIDFromContext = ztrace.SpanIDFromContext
  15. // TraceIDFromContext returns the trace id from ctx.
  16. TraceIDFromContext = ztrace.TraceIDFromContext
  17. )
  18. // PeerFromCtx returns the peer from ctx.
  19. func PeerFromCtx(ctx context.Context) string {
  20. p, ok := peer.FromContext(ctx)
  21. if !ok || p == nil {
  22. return ""
  23. }
  24. return p.Addr.String()
  25. }
  26. // SpanInfo returns the span info.
  27. func SpanInfo(fullMethod, peerAddress string) (string, []attribute.KeyValue) {
  28. attrs := []attribute.KeyValue{RPCSystemGRPC}
  29. name, mAttrs := ParseFullMethod(fullMethod)
  30. attrs = append(attrs, mAttrs...)
  31. attrs = append(attrs, PeerAttr(peerAddress)...)
  32. return name, attrs
  33. }
  34. // ParseFullMethod returns the method name and attributes.
  35. func ParseFullMethod(fullMethod string) (string, []attribute.KeyValue) {
  36. name := strings.TrimLeft(fullMethod, "/")
  37. parts := strings.SplitN(name, "/", 2)
  38. if len(parts) != 2 {
  39. // Invalid format, does not follow `/package.service/method`.
  40. return name, []attribute.KeyValue(nil)
  41. }
  42. var attrs []attribute.KeyValue
  43. if service := parts[0]; service != "" {
  44. attrs = append(attrs, semconv.RPCServiceKey.String(service))
  45. }
  46. if method := parts[1]; method != "" {
  47. attrs = append(attrs, semconv.RPCMethodKey.String(method))
  48. }
  49. return name, attrs
  50. }
  51. // PeerAttr returns the peer attributes.
  52. func PeerAttr(addr string) []attribute.KeyValue {
  53. host, port, err := net.SplitHostPort(addr)
  54. if err != nil {
  55. return nil
  56. }
  57. if len(host) == 0 {
  58. host = localhost
  59. }
  60. return []attribute.KeyValue{
  61. semconv.NetPeerIPKey.String(host),
  62. semconv.NetPeerPortKey.String(port),
  63. }
  64. }