Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Align gRPC server status code to span status code #3685

Merged
merged 19 commits into from
Apr 17, 2023
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
- AWS SDK add `rpc.system` attribute in `go.opentelemetry.io/contrib/instrumentation/github.com/aws/aws-sdk-go-v2/otelaws`. (#3582, #3617)
- Add the new `go.opentelemetry.io/contrib/instrgen` package to provide auto-generated source code instrumentation. (#3068, #3108)

### Changed

- Update `go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc` to align gRPC server span status with the changes in the OpenTelemetry specification. (#3685)

### Fixed

- Prevent taking from reservoir in AWS XRay Remote Sampler when there is zero capacity in `go.opentelemetry.io/contrib/samplers/aws/xray`. (#3684)
Expand Down
30 changes: 27 additions & 3 deletions instrumentation/google.golang.org/grpc/otelgrpc/interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,8 +342,8 @@ func UnaryServerInterceptor(opts ...Option) grpc.UnaryServerInterceptor {
resp, err := handler(ctx, req)
if err != nil {
s, _ := status.FromError(err)
statusCode = s.Code()
span.SetStatus(codes.Error, s.Message())
statusCode, msg := serverStatus(s)
span.SetStatus(statusCode, msg)
span.SetAttributes(statusCodeAttr(s.Code()))
messageSent.Event(ctx, 1, s.Proto())
} else {
Expand Down Expand Up @@ -435,7 +435,8 @@ func StreamServerInterceptor(opts ...Option) grpc.StreamServerInterceptor {
err := handler(srv, wrapServerStream(ctx, ss))
if err != nil {
s, _ := status.FromError(err)
span.SetStatus(codes.Error, s.Message())
statusCode, msg := serverStatus(s)
span.SetStatus(statusCode, msg)
span.SetAttributes(statusCodeAttr(s.Code()))
} else {
span.SetAttributes(statusCodeAttr(grpc_codes.OK))
Expand Down Expand Up @@ -499,3 +500,26 @@ func peerFromCtx(ctx context.Context) string {
func statusCodeAttr(c grpc_codes.Code) attribute.KeyValue {
return GRPCStatusCodeKey.Int64(int64(c))
}

// serverStatus returns a span status code and message for a given gRPC
// status code. It maps specific gRPC status codes to a corresponding span
// status code and message. This function is intended for use on the server
// side of a gRPC connection.
//
// If the gRPC status code is Unknown, DeadlineExceeded, Unimplemented,
// Internal, Unavailable, or DataLoss, it returns a span status code of Error
// and the message from the gRPC status. Otherwise, it returns a span status
// code of Unset and an empty message.
func serverStatus(grpcStatus *status.Status) (codes.Code, string) {
switch grpcStatus.Code() {
case grpc_codes.Unknown,
grpc_codes.DeadlineExceeded,
grpc_codes.Unimplemented,
grpc_codes.Internal,
grpc_codes.Unavailable,
grpc_codes.DataLoss:
return codes.Error, grpcStatus.Message()
default:
return codes.Unset, ""
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -583,24 +583,67 @@ func TestStreamClientInterceptorWithError(t *testing.T) {
assert.Equal(t, codes.Error, span.Status().Code)
}

func TestServerInterceptorError(t *testing.T) {
sr := tracetest.NewSpanRecorder()
tp := trace.NewTracerProvider(trace.WithSpanProcessor(sr))
usi := otelgrpc.UnaryServerInterceptor(otelgrpc.WithTracerProvider(tp))
deniedErr := status.Error(grpc_codes.PermissionDenied, "PERMISSION_DENIED_TEXT")
handler := func(_ context.Context, _ interface{}) (interface{}, error) {
return nil, deniedErr
var serverChecks = []struct {
pellared marked this conversation as resolved.
Show resolved Hide resolved
grpcCode grpc_codes.Code
wantSpanCode codes.Code
name string
}{
{
grpcCode: grpc_codes.OK,
wantSpanCode: codes.Unset,
name: "ok",
},
{
grpcCode: grpc_codes.Canceled,
wantSpanCode: codes.Unset,
name: "cancelled",
},
{
grpcCode: grpc_codes.NotFound,
wantSpanCode: codes.Unset,
name: "not.found",
},
{
grpcCode: grpc_codes.PermissionDenied,
wantSpanCode: codes.Unset,
name: "permission.denied",
},
{
grpcCode: grpc_codes.Unimplemented,
wantSpanCode: codes.Error,
name: "unimplemented",
},
{
grpcCode: grpc_codes.Internal,
wantSpanCode: codes.Error,
name: "internal",
},
{
grpcCode: grpc_codes.Unauthenticated,
wantSpanCode: codes.Unset,
name: "unauthenticated",
},
}

func assertServerErr(t *testing.T, err error, grpcCode grpc_codes.Code) {
// the error should be nil only if the gRPC code is OK, otherwise it should be the same as the gRPC error
if grpcCode == grpc_codes.OK {
assert.NoError(t, err)
} else {
assert.Equal(t, grpcCode, status.Code(err))
pellared marked this conversation as resolved.
Show resolved Hide resolved
}
_, err := usi(context.Background(), &grpc_testing.SimpleRequest{}, &grpc.UnaryServerInfo{}, handler)
require.Error(t, err)
assert.Equal(t, err, deniedErr)
}

span, ok := getSpanFromRecorder(sr, "")
if !ok {
t.Fatalf("failed to export error span")
func assertServerSpan(t *testing.T, span trace.ReadOnlySpan, wantSpanCode codes.Code, grpcCode grpc_codes.Code, grpcErr error) {
pellared marked this conversation as resolved.
Show resolved Hide resolved
// validate span status
assert.Equal(t, wantSpanCode, span.Status().Code)
if span.Status().Code == codes.Error {
assert.Contains(t, grpcErr.Error(), span.Status().Description)
} else {
assert.Empty(t, span.Status().Description)
pellared marked this conversation as resolved.
Show resolved Hide resolved
}
assert.Equal(t, codes.Error, span.Status().Code)
assert.Contains(t, deniedErr.Error(), span.Status().Description)

// validate grpc code span attribute
var codeAttr attribute.KeyValue
for _, a := range span.Attributes() {
if a.Key == otelgrpc.GRPCStatusCodeKey {
Expand All @@ -609,13 +652,68 @@ func TestServerInterceptorError(t *testing.T) {
}
}
if assert.True(t, codeAttr.Valid(), "attributes contain gRPC status code") {
assert.Equal(t, attribute.Int64Value(int64(grpc_codes.PermissionDenied)), codeAttr.Value)
assert.Equal(t, attribute.Int64Value(int64(grpcCode)), codeAttr.Value)
}
}

// TestUnaryServerInterceptor tests the server interceptor for unary RPCs.
func TestUnaryServerInterceptor(t *testing.T) {
sr := tracetest.NewSpanRecorder()
tp := trace.NewTracerProvider(trace.WithSpanProcessor(sr))
usi := otelgrpc.UnaryServerInterceptor(otelgrpc.WithTracerProvider(tp))
for _, check := range serverChecks {
t.Run(check.name, func(t *testing.T) {
grpcErr := status.Error(check.grpcCode, check.grpcCode.String())
handler := func(_ context.Context, _ interface{}) (interface{}, error) {
return nil, grpcErr
}
// call the unary interceptor
_, err := usi(context.Background(), &grpc_testing.SimpleRequest{}, &grpc.UnaryServerInfo{FullMethod: check.name}, handler)
assertServerErr(t, err, check.grpcCode)

// validate span
span, ok := getSpanFromRecorder(sr, check.name)
require.True(t, ok, "missing span %s", check.name)
assertServerSpan(t, span, check.wantSpanCode, check.grpcCode, grpcErr)

// validate events and their attributes
assert.Len(t, span.Events(), 2)
assert.ElementsMatch(t, []attribute.KeyValue{
attribute.Key("message.type").String("SENT"),
attribute.Key("message.id").Int(1),
}, span.Events()[1].Attributes)
})
}
}

type mockServerStream struct {
grpc.ServerStream
}

func (m *mockServerStream) Context() context.Context { return context.Background() }

// TestStreamServerInterceptor tests the server interceptor for streaming RPCs.
func TestStreamServerInterceptor(t *testing.T) {
sr := tracetest.NewSpanRecorder()
tp := trace.NewTracerProvider(trace.WithSpanProcessor(sr))
usi := otelgrpc.StreamServerInterceptor(otelgrpc.WithTracerProvider(tp))
for _, check := range serverChecks {
t.Run(check.name, func(t *testing.T) {
grpcErr := status.Error(check.grpcCode, check.grpcCode.String())
handler := func(_ interface{}, _ grpc.ServerStream) error {
return grpcErr
}

// call the stream interceptor
err := usi(&grpc_testing.SimpleRequest{}, &mockServerStream{}, &grpc.StreamServerInfo{FullMethod: check.name}, handler)
assertServerErr(t, err, check.grpcCode)

// validate span
span, ok := getSpanFromRecorder(sr, check.name)
require.True(t, ok, "missing span %s", check.name)
assertServerSpan(t, span, check.wantSpanCode, check.grpcCode, grpcErr)
})
}
assert.Len(t, span.Events(), 2)
assert.ElementsMatch(t, []attribute.KeyValue{
attribute.Key("message.type").String("SENT"),
attribute.Key("message.id").Int(1),
}, span.Events()[1].Attributes)
}

func TestParseFullMethod(t *testing.T) {
Expand Down