File: server.go

package info (click to toggle)
golang-github-openzipkin-zipkin-go 0.1.5%2Bgit20190103.2fd7f4a-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 532 kB
  • sloc: makefile: 22
file content (76 lines) | stat: -rw-r--r-- 2,221 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package grpc

import (
	"context"
	"github.com/openzipkin/zipkin-go"
	"github.com/openzipkin/zipkin-go/model"
	"github.com/openzipkin/zipkin-go/propagation/b3"
	"google.golang.org/grpc/metadata"
	"google.golang.org/grpc/stats"
)

type serverHandler struct {
	tracer      *zipkin.Tracer
	defaultTags map[string]string
}

// A ServerOption can be passed to NewServerHandler to customize the returned handler.
type ServerOption func(*serverHandler)

// ServerTags adds default Tags to inject into server spans.
func ServerTags(tags map[string]string) ServerOption {
	return func(h *serverHandler) {
		h.defaultTags = tags
	}
}

// NewServerHandler returns a stats.Handler which can be used with grpc.WithStatsHandler to add
// tracing to a gRPC server. The gRPC method name is used as the span name and by default the only
// tags are the gRPC status code if the call fails. Use ServerTags to add additional tags that
// should be applied to all spans.
func NewServerHandler(tracer *zipkin.Tracer, options ...ServerOption) stats.Handler {
	c := &serverHandler{
		tracer: tracer,
	}
	for _, option := range options {
		option(c)
	}
	return c
}

// HandleConn exists to satisfy gRPC stats.Handler.
func (s *serverHandler) HandleConn(ctx context.Context, cs stats.ConnStats) {
	// no-op
}

// TagConn exists to satisfy gRPC stats.Handler.
func (s *serverHandler) TagConn(ctx context.Context, cti *stats.ConnTagInfo) context.Context {
	// no-op
	return ctx
}

// HandleRPC implements per-RPC tracing and stats instrumentation.
func (s *serverHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) {
	handleRPC(ctx, rs)
}

// TagRPC implements per-RPC context management.
func (s *serverHandler) TagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context {
	md, ok := metadata.FromIncomingContext(ctx)
	// In practice, ok never seems to be false but add a defensive check.
	if !ok {
		md = metadata.New(nil)
	}

	name := spanName(rti)

	sc := s.tracer.Extract(b3.ExtractGRPC(&md))

	span := s.tracer.StartSpan(name, zipkin.Kind(model.Server), zipkin.Parent(sc), zipkin.RemoteEndpoint(remoteEndpointFromContext(ctx, "")))

	for k, v := range s.defaultTags {
		span.Tag(k, v)
	}

	return zipkin.NewContext(ctx, span)
}