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

Add gRPC-OpenTracing interceptors for Go #3

Merged
merged 5 commits into from
Sep 10, 2016
Merged
Show file tree
Hide file tree
Changes from 3 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
48 changes: 48 additions & 0 deletions go/otgrpc/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
# OpenTracing support for gRPC in Go

The `otgrpc` package makes it easy to add OpenTracing support to gRPC-based
systems in Go.

## Installation

```
go get github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc
```

## Usage on the client

Wherever you call `grpc.Dial`:

```
// You must have some sort of OpenTracing Tracer instance on hand.
var tracer opentracing.Tracer = ...
...

// Set up a connection to the server peer.
conn, err := grpc.Dial(
address,
... // other options
grpc.WithUnaryInterceptor(
otgrpc.OpenTracingClientInterceptor(tracer)))

// All future RPC activity involving `conn` will be automatically traced.
```

## Usage on the server

Wherever you call `grpc.NewServer`:

```
// You must have some sort of OpenTracing Tracer instance on hand.
var tracer opentracing.Tracer = ...
...

// Initialize the gRPC server.
s := grpc.NewServer(
... // other options
grpc.UnaryInterceptor(
otgrpc.OpenTracingServerInterceptor(tracer)))

// All future RPC activity involving `s` will be automatically traced.
```

68 changes: 68 additions & 0 deletions go/otgrpc/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package otgrpc

import (
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)

// OpenTracingClientInterceptor returns a grpc.UnaryClientInterceptor suitable
// for use in a grpc.Dial call.
//
// For example:
//
// conn, err := grpc.Dial(
// address,
// ..., // (existing DialOptions)
// grpc.WithUnaryInterceptor(otgrpc.OpenTracingClientInterceptor(tracer)))
//
// All gRPC client spans will inject the OpenTracing SpanContext into the gRPC
// metadata; they will also look in the context.Context for an active
// in-process parent Span and establish a ChildOf reference if such a parent
// Span could be found.
func OpenTracingClientInterceptor(tracer opentracing.Tracer, optFuncs ...Option) grpc.UnaryClientInterceptor {
otgrpcOpts := newOptions()
otgrpcOpts.apply(optFuncs...)
return func(
ctx context.Context,
method string,
req, resp interface{},
cc *grpc.ClientConn,
invoker grpc.UnaryInvoker,
opts ...grpc.CallOption,
) error {
var parentCtx opentracing.SpanContext
if parent := opentracing.SpanFromContext(ctx); parent != nil {
parentCtx = parent.Context()
}
clientSpan := tracer.StartSpan(
method,
opentracing.ChildOf(parentCtx),
ext.SpanKindRPCClient,
gRPCComponentTag,
)
defer clientSpan.Finish()
md, ok := metadata.FromContext(ctx)
if !ok {
md = metadata.New(nil)
}
mdWriter := metadataReaderWriter{md}
tracer.Inject(clientSpan.Context(), opentracing.TextMap, mdWriter)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's an error to handle, or a comment explaining why not.

ctx = metadata.NewContext(ctx, md)
if otgrpcOpts.logPayloads {
clientSpan.LogEventWithPayload("gRPC request", req)
}
err := invoker(ctx, method, req, resp, cc, opts...)
if err == nil {
if otgrpcOpts.logPayloads {
clientSpan.LogEventWithPayload("gRPC response", resp)
}
} else {
clientSpan.LogEventWithPayload("gRPC error", err)
ext.Error.Set(clientSpan, true)
}
return err
}
}
36 changes: 36 additions & 0 deletions go/otgrpc/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package otgrpc

// Option instances may be used in OpenTracing(Server|Client)Interceptor
// initialization.
//
// See this post about the "functional options" pattern:
// http://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis
type Option func(o *options)

// LogPayloads returns an Option that tells the OpenTracing instrumentation to
// try to log application payloads in both directions.
func LogPayloads() Option {
return func(o *options) {
o.logPayloads = true
}
}

// The internal-only options struct. Obviously overkill at the moment; but will
// scale well as production use dictates other configuration and tuning
// parameters.
type options struct {
logPayloads bool
}

// newOptions returns the default options.
func newOptions() *options {
return &options{
logPayloads: false,
}
}

func (o *options) apply(opts ...Option) {
for _, opt := range opts {
opt(o)
}
}
4 changes: 4 additions & 0 deletions go/otgrpc/package.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
// otgrpc provides OpenTracing support for any gRPC client or server in Go.
//
// See [go/otgrpc/README.md](https://github.com/grpc-ecosystem/grpc-opentracing/go/otgrpc/README.md)
package otgrpc
67 changes: 67 additions & 0 deletions go/otgrpc/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package otgrpc

import (
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/metadata"
)

// OpenTracingServerInterceptor returns a grpc.UnaryServerInterceptor suitable
// for use in a grpc.NewServer call.
//
// For example:
//
// s := grpc.NewServer(
// ..., // (existing ServerOptions)
// grpc.UnaryInterceptor(otgrpc.OpenTracingServerInterceptor(tracer)))
//
// All gRPC server spans will look for an OpenTracing SpanContext in the gRPC
// metadata; if found, the server span will act as the ChildOf that RPC
// SpanContext.
//
// Root or not, the server Span will be embedded in the context.Context for the
// application-specific gRPC handler(s) to access.
func OpenTracingServerInterceptor(tracer opentracing.Tracer, optFuncs ...Option) grpc.UnaryServerInterceptor {
otgrpcOpts := newOptions()
otgrpcOpts.apply(optFuncs...)
return func(
ctx context.Context,
req interface{},
info *grpc.UnaryServerInfo,
handler grpc.UnaryHandler,
) (resp interface{}, err error) {
md, ok := metadata.FromContext(ctx)
if !ok {
md = metadata.New(nil)
}
spanContext, err := tracer.Extract(opentracing.TextMap, metadataReaderWriter{md})
if err != nil && err != opentracing.ErrSpanContextNotFound {
// TODO: establish some sort of error reporting mechanism here. We
// don't know where to put such an error and must rely on Tracer
// implementations to do something appropriate for the time being.
}
span := tracer.StartSpan(
info.FullMethod,
ext.RPCServerOption(spanContext),
gRPCComponentTag,
)
defer span.Finish()

ctx = opentracing.ContextWithSpan(ctx, span)
if otgrpcOpts.logPayloads {
span.LogEventWithPayload("gRPC request", req)
}
resp, err = handler(ctx, req)
if err == nil {
if otgrpcOpts.logPayloads {
span.LogEventWithPayload("gRPC response", resp)
}
} else {
ext.Error.Set(span, true)
span.LogEventWithPayload("gRPC error", err)
}
return resp, err
}
}
38 changes: 38 additions & 0 deletions go/otgrpc/shared.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package otgrpc

import (
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"google.golang.org/grpc/metadata"
)

var (
// Morally a const:
gRPCComponentTag = opentracing.Tag{string(ext.Component), "gRPC"}
)

// metadataReaderWriter satisfies both the opentracing.TextMapReader and
// opentracing.TextMapWriter interfaces.
type metadataReaderWriter struct {
metadata.MD
}

func (w metadataReaderWriter) Set(key, val string) {
w.MD[key] = append(w.MD[key], val)
}

func (w metadataReaderWriter) ForeachKey(handler func(key, val string) error) error {
for k, vals := range w.MD {
for _, v := range vals {
if dk, dv, err := metadata.DecodeKeyValue(k, v); err == nil {
if err = handler(dk, dv); err != nil {
return err
}
} else {
return err
}
}
}

return nil
}