You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.6 KiB
Go
70 lines
1.6 KiB
Go
3 years ago
|
package trace
|
||
3 years ago
|
|
||
|
import (
|
||
|
"context"
|
||
|
"net"
|
||
|
"strings"
|
||
|
|
||
|
"go.opentelemetry.io/otel/attribute"
|
||
|
semconv "go.opentelemetry.io/otel/semconv/v1.4.0"
|
||
|
"google.golang.org/grpc/peer"
|
||
|
)
|
||
|
|
||
3 years ago
|
const localhost = "127.0.0.1"
|
||
|
|
||
3 years ago
|
// PeerFromCtx returns the peer from ctx.
|
||
3 years ago
|
func PeerFromCtx(ctx context.Context) string {
|
||
|
p, ok := peer.FromContext(ctx)
|
||
|
if !ok {
|
||
|
return ""
|
||
|
}
|
||
3 years ago
|
|
||
3 years ago
|
return p.Addr.String()
|
||
|
}
|
||
|
|
||
3 years ago
|
// SpanInfo returns the span info.
|
||
3 years ago
|
func SpanInfo(fullMethod, peerAddress string) (string, []attribute.KeyValue) {
|
||
|
attrs := []attribute.KeyValue{RPCSystemGRPC}
|
||
|
name, mAttrs := ParseFullMethod(fullMethod)
|
||
|
attrs = append(attrs, mAttrs...)
|
||
|
attrs = append(attrs, PeerAttr(peerAddress)...)
|
||
|
return name, attrs
|
||
|
}
|
||
|
|
||
3 years ago
|
// ParseFullMethod returns the method name and attributes.
|
||
3 years ago
|
func ParseFullMethod(fullMethod string) (string, []attribute.KeyValue) {
|
||
|
name := strings.TrimLeft(fullMethod, "/")
|
||
|
parts := strings.SplitN(name, "/", 2)
|
||
|
if len(parts) != 2 {
|
||
|
// Invalid format, does not follow `/package.service/method`.
|
||
|
return name, []attribute.KeyValue(nil)
|
||
|
}
|
||
|
|
||
|
var attrs []attribute.KeyValue
|
||
|
if service := parts[0]; service != "" {
|
||
|
attrs = append(attrs, semconv.RPCServiceKey.String(service))
|
||
|
}
|
||
|
if method := parts[1]; method != "" {
|
||
|
attrs = append(attrs, semconv.RPCMethodKey.String(method))
|
||
|
}
|
||
3 years ago
|
|
||
3 years ago
|
return name, attrs
|
||
|
}
|
||
|
|
||
3 years ago
|
// PeerAttr returns the peer attributes.
|
||
3 years ago
|
func PeerAttr(addr string) []attribute.KeyValue {
|
||
|
host, port, err := net.SplitHostPort(addr)
|
||
|
if err != nil {
|
||
|
return []attribute.KeyValue(nil)
|
||
|
}
|
||
|
|
||
3 years ago
|
if len(host) == 0 {
|
||
|
host = localhost
|
||
3 years ago
|
}
|
||
|
|
||
|
return []attribute.KeyValue{
|
||
|
semconv.NetPeerIPKey.String(host),
|
||
|
semconv.NetPeerPortKey.String(port),
|
||
|
}
|
||
|
}
|