-
Notifications
You must be signed in to change notification settings - Fork 4.4k
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
stats/opentelemetry: Introduce Tracing API #7852
Open
aranjans
wants to merge
17
commits into
grpc:master
Choose a base branch
from
aranjans:a72
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+739
−78
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
cfb49fc
Implement A72: OpenTelemetry Tracing
aranjans 3dff313
Add go.mod for stats/opentelemetry
aranjans 4ae07dd
Update examples go.mod
aranjans 38eabb9
Rebase with Purnesh's PR
aranjans 30257cf
refactor and exclude otel from examples
aranjans 0e01810
Revert go.mod files
aranjans cea60d4
Rebase with grpc-go master
aranjans 39f7693
Rebase with grpc-go master
aranjans 2a26fc2
remove attemptTraceInfo and use attemptInfo instead
aranjans 8cb8222
Use NewOutgoingCarrier to inject into GRPCTraceBinPropagator
aranjans b9f23ee
rename commonHandler to statsHandler
aranjans 729713b
nits
aranjans 382d053
make vet happy
aranjans 8e78478
addressed nits and comments from Purnesh
aranjans 60bb987
addressed comments
aranjans 82bdbd7
Rebase with master
aranjans ce57921
Merge branch 'master' into a72
aranjans File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -18,10 +18,15 @@ package opentelemetry | |
|
||
import ( | ||
"context" | ||
"strings" | ||
"sync/atomic" | ||
"time" | ||
|
||
"go.opentelemetry.io/otel" | ||
otelcodes "go.opentelemetry.io/otel/codes" | ||
"go.opentelemetry.io/otel/trace" | ||
"google.golang.org/grpc" | ||
grpccodes "google.golang.org/grpc/codes" | ||
estats "google.golang.org/grpc/experimental/stats" | ||
istats "google.golang.org/grpc/internal/stats" | ||
"google.golang.org/grpc/metadata" | ||
|
@@ -33,6 +38,7 @@ import ( | |
) | ||
|
||
type clientStatsHandler struct { | ||
statsHandler | ||
estats.MetricsRecorder | ||
options Options | ||
clientMetrics clientMetrics | ||
|
@@ -68,6 +74,15 @@ func (h *clientStatsHandler) initializeMetrics() { | |
rm.registerMetrics(metrics, meter) | ||
} | ||
|
||
func (h *clientStatsHandler) initializeTracing() { | ||
if isTracingDisabled(h.options.TraceOptions) { | ||
return | ||
} | ||
|
||
otel.SetTextMapPropagator(h.options.TraceOptions.TextMapPropagator) | ||
otel.SetTracerProvider(h.options.TraceOptions.TracerProvider) | ||
} | ||
|
||
func (h *clientStatsHandler) unaryInterceptor(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { | ||
ci := &callInfo{ | ||
target: cc.CanonicalTarget(), | ||
|
@@ -85,8 +100,12 @@ func (h *clientStatsHandler) unaryInterceptor(ctx context.Context, method string | |
} | ||
|
||
startTime := time.Now() | ||
var span *trace.Span | ||
if !isTracingDisabled(h.options.TraceOptions) { | ||
ctx, span = h.createCallTraceSpan(ctx, method) | ||
} | ||
err := invoker(ctx, method, req, reply, cc, opts...) | ||
h.perCallMetrics(ctx, err, startTime, ci) | ||
h.perCallTracesAndMetrics(ctx, err, startTime, ci, span) | ||
return err | ||
} | ||
|
||
|
@@ -119,22 +138,50 @@ func (h *clientStatsHandler) streamInterceptor(ctx context.Context, desc *grpc.S | |
} | ||
|
||
startTime := time.Now() | ||
|
||
var span *trace.Span | ||
if !isTracingDisabled(h.options.TraceOptions) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. same suggestion here |
||
ctx, span = h.createCallTraceSpan(ctx, method) | ||
} | ||
callback := func(err error) { | ||
h.perCallMetrics(ctx, err, startTime, ci) | ||
h.perCallTracesAndMetrics(ctx, err, startTime, ci, span) | ||
} | ||
opts = append([]grpc.CallOption{grpc.OnFinish(callback)}, opts...) | ||
return streamer(ctx, desc, cc, method, opts...) | ||
} | ||
|
||
func (h *clientStatsHandler) perCallMetrics(ctx context.Context, err error, startTime time.Time, ci *callInfo) { | ||
callLatency := float64(time.Since(startTime)) / float64(time.Second) // calculate ASAP | ||
attrs := otelmetric.WithAttributeSet(otelattribute.NewSet( | ||
otelattribute.String("grpc.method", ci.method), | ||
otelattribute.String("grpc.target", ci.target), | ||
otelattribute.String("grpc.status", canonicalString(status.Code(err))), | ||
)) | ||
h.clientMetrics.callDuration.Record(ctx, callLatency, attrs) | ||
// perCallTracesAndMetrics records per call trace spans and metrics. | ||
func (h *clientStatsHandler) perCallTracesAndMetrics(ctx context.Context, err error, startTime time.Time, ci *callInfo, ts *trace.Span) { | ||
if !isTracingDisabled(h.options.TraceOptions) && ts != nil { | ||
s := status.Convert(err) | ||
if s.Code() == grpccodes.OK { | ||
(*ts).SetStatus(otelcodes.Ok, s.Message()) | ||
} else { | ||
(*ts).SetStatus(otelcodes.Error, s.Message()) | ||
} | ||
(*ts).End() | ||
} | ||
if !isMetricsDisabled(h.options.MetricsOptions) { | ||
callLatency := float64(time.Since(startTime)) / float64(time.Second) | ||
attrs := otelmetric.WithAttributeSet(otelattribute.NewSet( | ||
otelattribute.String("grpc.method", ci.method), | ||
otelattribute.String("grpc.target", ci.target), | ||
otelattribute.String("grpc.status", canonicalString(status.Code(err))), | ||
)) | ||
h.clientMetrics.callDuration.Record(ctx, callLatency, attrs) | ||
} | ||
} | ||
|
||
// createCallTraceSpan creates a call span to put in the provided context using | ||
// provided TraceProvider. If TraceProvider is nil, it returns context as is. | ||
func (h *clientStatsHandler) createCallTraceSpan(ctx context.Context, method string) (context.Context, *trace.Span) { | ||
if h.options.TraceOptions.TracerProvider == nil { | ||
logger.Error("TraceProvider is not provided in trace options") | ||
return ctx, nil | ||
} | ||
mn := strings.Replace(removeLeadingSlash(method), "/", ".", -1) | ||
tracer := otel.Tracer("grpc-open-telemetry") | ||
ctx, span := tracer.Start(ctx, mn, trace.WithSpanKind(trace.SpanKindClient)) | ||
return ctx, &span | ||
} | ||
|
||
// TagConn exists to satisfy stats.Handler. | ||
|
@@ -163,15 +210,29 @@ func (h *clientStatsHandler) TagRPC(ctx context.Context, info *stats.RPCTagInfo) | |
} | ||
ctx = istats.SetLabels(ctx, labels) | ||
} | ||
ai := &attemptInfo{ // populates information about RPC start. | ||
ai := &attemptInfo{ | ||
startTime: time.Now(), | ||
xdsLabels: labels.TelemetryLabels, | ||
method: info.FullMethodName, | ||
} | ||
ri := &rpcInfo{ | ||
ai: ai, | ||
if !isTracingDisabled(h.options.TraceOptions) { | ||
callSpan := trace.SpanFromContext(ctx) | ||
if info.NameResolutionDelay { | ||
callSpan.AddEvent("Delayed name resolution complete") | ||
} | ||
var newAI *attemptInfo | ||
ctx, newAI = h.traceTagRPC(trace.ContextWithSpan(ctx, callSpan), info) | ||
// Update the ai with values from updated attempt info. | ||
newAI.startTime = ai.startTime | ||
newAI.xdsLabels = ai.xdsLabels | ||
newAI.method = ai.method | ||
|
||
ai = newAI | ||
} | ||
return setRPCInfo(ctx, ri) | ||
|
||
return setRPCInfo(ctx, &rpcInfo{ | ||
ai: ai, | ||
}) | ||
} | ||
|
||
func (h *clientStatsHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) { | ||
|
@@ -180,7 +241,12 @@ func (h *clientStatsHandler) HandleRPC(ctx context.Context, rs stats.RPCStats) { | |
logger.Error("ctx passed into client side stats handler metrics event handling has no client attempt data present") | ||
return | ||
} | ||
h.processRPCEvent(ctx, rs, ri.ai) | ||
if !isMetricsDisabled(h.options.MetricsOptions) { | ||
h.processRPCEvent(ctx, rs, ri.ai) | ||
} | ||
if !isTracingDisabled(h.options.TraceOptions) { | ||
h.populateSpan(ctx, rs, ri.ai) | ||
} | ||
} | ||
|
||
func (h *clientStatsHandler) processRPCEvent(ctx context.Context, s stats.RPCStats, ai *attemptInfo) { | ||
|
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
how about we pass the method to
perCallTracesAndMetrics
and create the trace span there if tracing is not disabled? it is because we are already checking traces disable inperCallTracesAndMetrics
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We need to have create call span here as we need to add event for "name resolution delay", and this info is only available in RPCTagInfo. One alternative way is to have a struct for nameResolutionDelay as a key of context metadata, but I don't think it'd be good idea to do that.
Based on offline discussion, going ahead with earlier approach.