utils.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package opentelemetry
  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. func PeerFromCtx(ctx context.Context) string {
  11. p, ok := peer.FromContext(ctx)
  12. if !ok {
  13. return ""
  14. }
  15. return p.Addr.String()
  16. }
  17. func SpanInfo(fullMethod, peerAddress string) (string, []attribute.KeyValue) {
  18. attrs := []attribute.KeyValue{RPCSystemGRPC}
  19. name, mAttrs := ParseFullMethod(fullMethod)
  20. attrs = append(attrs, mAttrs...)
  21. attrs = append(attrs, PeerAttr(peerAddress)...)
  22. return name, attrs
  23. }
  24. func ParseFullMethod(fullMethod string) (string, []attribute.KeyValue) {
  25. name := strings.TrimLeft(fullMethod, "/")
  26. parts := strings.SplitN(name, "/", 2)
  27. if len(parts) != 2 {
  28. // Invalid format, does not follow `/package.service/method`.
  29. return name, []attribute.KeyValue(nil)
  30. }
  31. var attrs []attribute.KeyValue
  32. if service := parts[0]; service != "" {
  33. attrs = append(attrs, semconv.RPCServiceKey.String(service))
  34. }
  35. if method := parts[1]; method != "" {
  36. attrs = append(attrs, semconv.RPCMethodKey.String(method))
  37. }
  38. return name, attrs
  39. }
  40. func PeerAttr(addr string) []attribute.KeyValue {
  41. host, port, err := net.SplitHostPort(addr)
  42. if err != nil {
  43. return []attribute.KeyValue(nil)
  44. }
  45. if host == "" {
  46. host = "127.0.0.1"
  47. }
  48. return []attribute.KeyValue{
  49. semconv.NetPeerIPKey.String(host),
  50. semconv.NetPeerPortKey.String(port),
  51. }
  52. }