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 support for tracing via OpenTelemetry #254
Merged
casualjim
merged 13 commits into
go-openapi:master
from
josephwoodward:add-opentelemetry-support
Nov 28, 2022
Merged
Changes from 4 commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
bac160e
Initial PR to add support for OTEL
josephwoodward 75bec98
Start to add span attributes covered by test
josephwoodward f414288
Include more span attributes
josephwoodward e390757
Continue to work on setting appropriate attributes
josephwoodward 14ee16f
Add nil context test case
josephwoodward b3ce5f1
Ensure status captures error message
josephwoodward 9aa3bfd
Add scheme
josephwoodward d09ae3b
Address remaining test implementation, add functional options
josephwoodward eef3104
Remove unused package reference
josephwoodward 601824c
Add support for setting span name
josephwoodward f318eb6
Clean up implementation
josephwoodward 0ebe6da
Bump go version in github ci
josephwoodward f454d66
Bump go to 1.18
josephwoodward File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,111 @@ | ||
package client | ||
|
||
import ( | ||
"net/http" | ||
|
||
"github.com/go-openapi/runtime" | ||
"github.com/go-openapi/strfmt" | ||
"go.opentelemetry.io/otel" | ||
"go.opentelemetry.io/otel/attribute" | ||
"go.opentelemetry.io/otel/codes" | ||
semconv "go.opentelemetry.io/otel/semconv/v1.12.0" | ||
"go.opentelemetry.io/otel/trace" | ||
) | ||
|
||
type openTelemetryTransport struct { | ||
transport runtime.ClientTransport | ||
host string | ||
opts []trace.SpanStartOption | ||
} | ||
|
||
func newOpenTelemetryTransport(transport runtime.ClientTransport, host string, opts []trace.SpanStartOption) runtime.ClientTransport { | ||
return &openTelemetryTransport{ | ||
transport: transport, | ||
host: host, | ||
opts: opts, | ||
} | ||
} | ||
|
||
func (t *openTelemetryTransport) Submit(op *runtime.ClientOperation) (interface{}, error) { | ||
if op.Context == nil { | ||
return t.transport.Submit(op) | ||
} | ||
|
||
params := op.Params | ||
reader := op.Reader | ||
|
||
var span trace.Span | ||
defer func() { | ||
if span != nil { | ||
span.End() | ||
} | ||
}() | ||
|
||
op.Params = runtime.ClientRequestWriterFunc(func(req runtime.ClientRequest, reg strfmt.Registry) error { | ||
span = createOpenTelemetryClientSpan(op, req.GetHeaderParams(), t.host, t.opts) | ||
return params.WriteToRequest(req, reg) | ||
}) | ||
|
||
op.Reader = runtime.ClientResponseReaderFunc(func(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) { | ||
if span != nil { | ||
statusCode := response.Code() | ||
span.SetAttributes(attribute.Int(string(semconv.HTTPStatusCodeKey), statusCode)) | ||
span.SetStatus(semconv.SpanStatusFromHTTPStatusCodeAndSpanKind(statusCode, trace.SpanKindClient)) | ||
} | ||
|
||
return reader.ReadResponse(response, consumer) | ||
}) | ||
|
||
submit, err := t.transport.Submit(op) | ||
if err != nil && span != nil { | ||
span.RecordError(err) | ||
span.SetStatus(codes.Error, "") | ||
} | ||
|
||
return submit, err | ||
} | ||
|
||
func createOpenTelemetryClientSpan(op *runtime.ClientOperation, _ http.Header, host string, opts []trace.SpanStartOption) trace.Span { | ||
ctx := op.Context | ||
span := trace.SpanFromContext(ctx) | ||
|
||
if span != nil { | ||
// TODO: Can we get the version number for use with trace.WithInstrumentationVersion? | ||
tracer := otel.GetTracerProvider().Tracer("") | ||
|
||
ctx, span = tracer.Start(ctx, operationName(op), opts...) | ||
op.Context = ctx | ||
|
||
span.SetAttributes( | ||
attribute.String("net.peer.name", host), | ||
// attribute.String("net.peer.port", ""), | ||
attribute.String(string(semconv.HTTPRouteKey), op.PathPattern), | ||
attribute.String(string(semconv.HTTPMethodKey), op.Method), | ||
attribute.String("span.kind", trace.SpanKindClient.String()), | ||
//TODO: Figure out the best way to get the scheme? | ||
attribute.String("http.scheme", op.Schemes[0]), | ||
) | ||
|
||
return span | ||
} | ||
|
||
// if span != nil { | ||
// opts = append(opts, ext.SpanKindRPCClient) | ||
// span, _ = opentracing.StartSpanFromContextWithTracer( | ||
// ctx, span.Tracer(), operationName(op), opts...) | ||
|
||
// ext.Component.Set(span, "go-openapi") | ||
// ext.PeerHostname.Set(span, host) | ||
// span.SetTag("http.path", op.PathPattern) | ||
// ext.HTTPMethod.Set(span, op.Method) | ||
|
||
// _ = span.Tracer().Inject( | ||
// span.Context(), | ||
// opentracing.HTTPHeaders, | ||
// opentracing.HTTPHeadersCarrier(header)) | ||
|
||
// return span | ||
// } | ||
|
||
return nil | ||
} |
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 |
---|---|---|
@@ -0,0 +1,99 @@ | ||
package client | ||
|
||
import ( | ||
"context" | ||
"testing" | ||
|
||
"github.com/go-openapi/runtime" | ||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
|
||
"go.opentelemetry.io/otel" | ||
"go.opentelemetry.io/otel/attribute" | ||
"go.opentelemetry.io/otel/codes" | ||
tracesdk "go.opentelemetry.io/otel/sdk/trace" | ||
"go.opentelemetry.io/otel/sdk/trace/tracetest" | ||
"go.opentelemetry.io/otel/trace" | ||
) | ||
|
||
func Test_OpenTelemetryRuntime_submit(t *testing.T) { | ||
t.Parallel() | ||
|
||
exporter := tracetest.NewInMemoryExporter() | ||
|
||
tp := tracesdk.NewTracerProvider( | ||
tracesdk.WithSampler(tracesdk.AlwaysSample()), | ||
tracesdk.WithSyncer(exporter), | ||
) | ||
|
||
otel.SetTracerProvider(tp) | ||
|
||
tracer := tp.Tracer("go-runtime") | ||
ctx, _ := tracer.Start(context.Background(), "op") | ||
|
||
assertOpenTelemetrySubmit(t, testOperation(ctx), exporter, 1) | ||
} | ||
|
||
// func Test_OpenTelemetryRuntime_submit_nilAuthInfo(t *testing.T) { | ||
// t.Parallel() | ||
// tracer := mocktracer.New() | ||
// _, ctx := opentracing.StartSpanFromContextWithTracer(context.Background(), tracer, "op") | ||
// operation := testOperation(ctx) | ||
// operation.AuthInfo = nil | ||
// testOpenTelemetrySubmit(t, operation, tracer, 1) | ||
// } | ||
|
||
// func Test_OpenTelemetryRuntime_submit_nilContext(t *testing.T) { | ||
// t.Parallel() | ||
// tracer := mocktracer.New() | ||
// _, ctx := opentracing.StartSpanFromContextWithTracer(context.Background(), tracer, "op") | ||
// operation := testOperation(ctx) | ||
// operation.Context = nil | ||
// testOpenTelemetrySubmit(t, operation, tracer, 0) // just don't panic | ||
// } | ||
|
||
// func Test_injectOpenTelemetrySpanContext(t *testing.T) { | ||
// t.Parallel() | ||
// tracer := mocktracer.New() | ||
// _, ctx := opentracing.StartSpanFromContextWithTracer(context.Background(), tracer, "op") | ||
// header := map[string][]string{} | ||
// createOpenTelemetryClientSpan(testOperation(ctx), header, "", nil) | ||
|
||
// // values are random - just check that something was injected | ||
// assert.Len(t, header, 3) | ||
// } | ||
|
||
func assertOpenTelemetrySubmit(t *testing.T, operation *runtime.ClientOperation, exporter *tracetest.InMemoryExporter, expectedSpanCount int) { | ||
header := map[string][]string{} | ||
r := newOpenTelemetryTransport(&mockRuntime{runtime.TestClientRequest{Headers: header}}, | ||
"remote_host", | ||
[]trace.SpanStartOption{}) | ||
|
||
// // opentracing.Tag{ | ||
// Key: string(ext.PeerService), | ||
// Value: "service", | ||
// } | ||
|
||
_, err := r.Submit(operation) | ||
require.NoError(t, err) | ||
|
||
spans := exporter.GetSpans() | ||
assert.Len(t, spans, expectedSpanCount) | ||
|
||
if expectedSpanCount == 1 { | ||
span := spans[0] | ||
assert.Equal(t, "getCluster", span.Name) | ||
assert.Equal(t, span.Status.Code, codes.Error) | ||
assert.Equal(t, []attribute.KeyValue{ | ||
// "component": "go-openapi", | ||
attribute.String("net.peer.name", "remote_host"), | ||
attribute.String("http.route", "/kubernetes-clusters/{cluster_id}"), | ||
attribute.String("http.method", "GET"), | ||
attribute.String("span.kind", trace.SpanKindClient.String()), | ||
attribute.String("http.scheme", "https"), | ||
attribute.Int("http.status_code", 490), | ||
// "peer.service": "service", | ||
// "error": true, | ||
}, span.Attributes) | ||
} | ||
} |
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
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.
Hi @casualjim, can you offer any pointers on the best way to get the scheme? I don't appear to have access to the underlying
http.Request
object to check the existence of theTLS
field (which is one common way to work out the scheme)