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 12 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 recent changes in the OpenTelemetry specification (see `https://github.com/open-telemetry/opentelemetry-specification/pull/3333`).
FaranIdo marked this conversation as resolved.
Show resolved Hide resolved

### 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,39 +583,150 @@ func TestStreamClientInterceptorWithError(t *testing.T) {
assert.Equal(t, codes.Error, span.Status().Code)
}

func TestServerInterceptorError(t *testing.T) {
var serverChecks = []struct {
pellared marked this conversation as resolved.
Show resolved Hide resolved
grpcCode grpc_codes.Code
spanCode codes.Code
pellared marked this conversation as resolved.
Show resolved Hide resolved
name string
pellared marked this conversation as resolved.
Show resolved Hide resolved
}{
{
grpcCode: grpc_codes.OK,
spanCode: codes.Unset,
name: "ok",
},
{
grpcCode: grpc_codes.Canceled,
spanCode: codes.Unset,
name: "cancelled",
},
{
grpcCode: grpc_codes.NotFound,
spanCode: codes.Unset,
name: "not.found",
},
{
grpcCode: grpc_codes.PermissionDenied,
spanCode: codes.Unset,
name: "permission.denied",
},
{
grpcCode: grpc_codes.Unimplemented,
spanCode: codes.Error,
name: "unimplemented",
},
{
grpcCode: grpc_codes.Internal,
spanCode: codes.Error,
name: "internal",
},
{
grpcCode: grpc_codes.Unauthenticated,
spanCode: codes.Unset,
name: "unauthenticated",
},
}

func UnaryServerInterceptor(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
}
_, err := usi(context.Background(), &grpc_testing.SimpleRequest{}, &grpc.UnaryServerInfo{}, handler)
require.Error(t, err)
assert.Equal(t, err, deniedErr)
for _, check := range serverChecks {
pellared marked this conversation as resolved.
Show resolved Hide resolved
grpcErr := status.Error(check.grpcCode, check.grpcCode.String())
handler := func(_ context.Context, _ interface{}) (interface{}, error) {
return nil, grpcErr
}
_, err := usi(context.Background(), &grpc_testing.SimpleRequest{}, &grpc.UnaryServerInfo{FullMethod: check.name}, handler)
// the error should be nil only if the gRPC code is OK, otherwise it should be the same as the gRPC error
if check.grpcCode != grpc_codes.OK {
require.Error(t, err)
assert.Equal(t, err, grpcErr)
} else {
require.NoError(t, err)
}

span, ok := getSpanFromRecorder(sr, "")
if !ok {
t.Fatalf("failed to export error span")
}
assert.Equal(t, codes.Error, span.Status().Code)
assert.Contains(t, deniedErr.Error(), span.Status().Description)
var codeAttr attribute.KeyValue
for _, a := range span.Attributes() {
if a.Key == otelgrpc.GRPCStatusCodeKey {
codeAttr = a
break
span, ok := getSpanFromRecorder(sr, check.name)
if !assert.True(t, ok, "missing span %q", check.name) {
continue
}

// validate span status
assert.Equal(t, check.spanCode, span.Status().Code)
if span.Status().Code == codes.Error {
assert.Contains(t, grpcErr.Error(), span.Status().Description)
} else {
assert.Empty(t, span.Status().Description)
}

// validate span attributes
var codeAttr attribute.KeyValue
for _, a := range span.Attributes() {
if a.Key == otelgrpc.GRPCStatusCodeKey {
codeAttr = a
break
}
}
if assert.True(t, codeAttr.Valid(), "attributes contain gRPC status code") {
assert.Equal(t, attribute.Int64Value(int64(check.grpcCode)), codeAttr.Value)
}

// 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)
pellared marked this conversation as resolved.
Show resolved Hide resolved
}
if assert.True(t, codeAttr.Valid(), "attributes contain gRPC status code") {
assert.Equal(t, attribute.Int64Value(int64(grpc_codes.PermissionDenied)), codeAttr.Value)
}

type mockServerStream struct {
grpc.ServerStream
}

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

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

err := usi(&grpc_testing.SimpleRequest{}, &mockServerStream{}, &grpc.StreamServerInfo{FullMethod: check.name}, handler)
// the error should be nil only if the gRPC code is OK, otherwise it should be the same as the gRPC error
if check.grpcCode != grpc_codes.OK {
require.Error(t, err)
assert.Equal(t, err, grpcErr)
} else {
require.NoError(t, err)
}

span, ok := getSpanFromRecorder(sr, check.name)
if !assert.True(t, ok, "missing span %q", check.name) {
continue
}

// validate span status
assert.Equal(t, check.spanCode, span.Status().Code)
if span.Status().Code == codes.Error {
assert.Contains(t, grpcErr.Error(), span.Status().Description)
} else {
assert.Empty(t, span.Status().Description)
}

// validate span attributes
var codeAttr attribute.KeyValue
for _, a := range span.Attributes() {
if a.Key == otelgrpc.GRPCStatusCodeKey {
codeAttr = a
break
}
}
if assert.True(t, codeAttr.Valid(), "attributes contain gRPC status code") {
assert.Equal(t, attribute.Int64Value(int64(check.grpcCode)), codeAttr.Value)
}
}
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