|
| 1 | +package trace |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "go.opentelemetry.io/otel/attribute" |
| 9 | + semconv "go.opentelemetry.io/otel/semconv/v1.4.0" |
| 10 | + "google.golang.org/grpc/peer" |
| 11 | +) |
| 12 | + |
| 13 | +const localhost = "127.0.0.1" |
| 14 | + |
| 15 | +// PeerFromCtx returns the peer from ctx. |
| 16 | +func PeerFromCtx(ctx context.Context) string { |
| 17 | + p, ok := peer.FromContext(ctx) |
| 18 | + if !ok || p == nil { |
| 19 | + return "" |
| 20 | + } |
| 21 | + |
| 22 | + return p.Addr.String() |
| 23 | +} |
| 24 | + |
| 25 | +// SpanInfo returns the span info. |
| 26 | +func SpanInfo(fullMethod, peerAddress string) (string, []attribute.KeyValue) { |
| 27 | + attrs := []attribute.KeyValue{RPCSystemGRPC} |
| 28 | + name, mAttrs := ParseFullMethod(fullMethod) |
| 29 | + attrs = append(attrs, mAttrs...) |
| 30 | + attrs = append(attrs, PeerAttr(peerAddress)...) |
| 31 | + return name, attrs |
| 32 | +} |
| 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 | + |
| 43 | + var attrs []attribute.KeyValue |
| 44 | + if service := parts[0]; service != "" { |
| 45 | + attrs = append(attrs, semconv.RPCServiceKey.String(service)) |
| 46 | + } |
| 47 | + if method := parts[1]; method != "" { |
| 48 | + attrs = append(attrs, semconv.RPCMethodKey.String(method)) |
| 49 | + } |
| 50 | + |
| 51 | + return name, attrs |
| 52 | +} |
| 53 | + |
| 54 | +// PeerAttr returns the peer attributes. |
| 55 | +func PeerAttr(addr string) []attribute.KeyValue { |
| 56 | + host, port, err := net.SplitHostPort(addr) |
| 57 | + if err != nil { |
| 58 | + return nil |
| 59 | + } |
| 60 | + |
| 61 | + if len(host) == 0 { |
| 62 | + host = localhost |
| 63 | + } |
| 64 | + |
| 65 | + return []attribute.KeyValue{ |
| 66 | + semconv.NetPeerIPKey.String(host), |
| 67 | + semconv.NetPeerPortKey.String(port), |
| 68 | + } |
| 69 | +} |
0 commit comments