1 // Copyright 2018, OpenCensus Authors
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
18 "go.opencensus.io/trace"
19 "golang.org/x/net/context"
21 "google.golang.org/grpc/stats"
24 // ServerHandler implements gRPC stats.Handler recording OpenCensus stats and
25 // traces. Use with gRPC servers.
27 // When installed (see Example), tracing metadata is read from inbound RPCs
28 // by default. If no tracing metadata is present, or if the tracing metadata is
29 // present but the SpanContext isn't sampled, then a new trace may be started
30 // (as determined by Sampler).
31 type ServerHandler struct {
32 // IsPublicEndpoint may be set to true to always start a new trace around
33 // each RPC. Any SpanContext in the RPC metadata will be added as a linked
34 // span instead of making it the parent of the span created around the
37 // Be aware that if you leave this false (the default) on a public-facing
38 // server, callers will be able to send tracing metadata in gRPC headers
39 // and trigger traces in your backend.
42 // StartOptions to use for to spans started around RPCs handled by this server.
44 // These will apply even if there is tracing metadata already
45 // present on the inbound RPC but the SpanContext is not sampled. This
46 // ensures that each service has some opportunity to be traced. If you would
47 // like to not add any additional traces for this gRPC service, set:
49 // StartOptions.Sampler = trace.ProbabilitySampler(0.0)
51 // StartOptions.SpanKind will always be set to trace.SpanKindServer
52 // for spans started by this handler.
53 StartOptions trace.StartOptions
56 var _ stats.Handler = (*ServerHandler)(nil)
58 // HandleConn exists to satisfy gRPC stats.Handler.
59 func (s *ServerHandler) HandleConn(ctx context.Context, cs stats.ConnStats) {
63 // TagConn exists to satisfy gRPC stats.Handler.
64 func (s *ServerHandler) TagConn(ctx context.Context, cti *stats.ConnTagInfo) context.Context {
69 // HandleRPC implements per-RPC tracing and stats instrumentation.
70 func (s *ServerHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) {
71 traceHandleRPC(ctx, rs)
72 statsHandleRPC(ctx, rs)
75 // TagRPC implements per-RPC context management.
76 func (s *ServerHandler) TagRPC(ctx context.Context, rti *stats.RPCTagInfo) context.Context {
77 ctx = s.traceTagRPC(ctx, rti)
78 ctx = s.statsTagRPC(ctx, rti)