utils.go 1.6 KB

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