-
Notifications
You must be signed in to change notification settings - Fork 1.2k
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 distributed tracing framework #1211
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
6148b41
Add tracing framework
bboreham 1371ba8
Connect logging to tracing
bboreham e3408a7
Try to get GroupVersionKind to log Create()
bboreham d4bc91a
Convert from OpenTracing to OpenTelemetry
bboreham ec80672
Update go.mod after conversion to OpenTelemetry
bboreham 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
Large diffs are not rendered by default.
Oops, something went wrong.
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,84 @@ | ||
package tracing | ||
|
||
import ( | ||
"context" | ||
|
||
"go.opentelemetry.io/otel/api/global" | ||
"go.opentelemetry.io/otel/api/trace" | ||
"k8s.io/apimachinery/pkg/api/meta" | ||
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" | ||
"k8s.io/apimachinery/pkg/runtime" | ||
) | ||
|
||
// TraceAnnotationPrefix is where we store span contexts in Kubernetes annotations | ||
const TraceAnnotationPrefix string = "trace.kubernetes.io/" | ||
|
||
// Store tracing propagation inside Kubernetes annotations | ||
type annotationsCarrier map[string]string | ||
|
||
// Get implements otel.TextMapCarrier | ||
func (a annotationsCarrier) Get(key string) string { | ||
return a[TraceAnnotationPrefix+key] | ||
} | ||
|
||
// Set implements otel.TextMapCarrier | ||
func (a annotationsCarrier) Set(key string, value string) { | ||
a[TraceAnnotationPrefix+key] = value | ||
} | ||
|
||
// SpanFromAnnotations takes a map as found in Kubernetes objects and | ||
// makes a new Span parented on the context found there, or nil if not found. | ||
func SpanFromAnnotations(ctx context.Context, name string, annotations map[string]string) (context.Context, trace.Span) { | ||
innerCtx := spanContextFromAnnotations(ctx, annotations) | ||
if innerCtx == ctx { | ||
return ctx, nil | ||
} | ||
return global.Tracer(libName).Start(innerCtx, name) | ||
} | ||
|
||
func spanContextFromAnnotations(ctx context.Context, annotations map[string]string) context.Context { | ||
return global.TextMapPropagator().Extract(ctx, annotationsCarrier(annotations)) | ||
} | ||
|
||
// AddTraceAnnotation adds an annotation encoding current span ID | ||
func AddTraceAnnotation(ctx context.Context, annotations map[string]string) { | ||
global.TextMapPropagator().Inject(ctx, annotationsCarrier(annotations)) | ||
} | ||
|
||
// AddTraceAnnotationToUnstructured adds an annotation encoding current span ID to all objects | ||
// Objects are modified in-place. | ||
func AddTraceAnnotationToUnstructured(ctx context.Context, objs []unstructured.Unstructured) error { | ||
for _, o := range objs { | ||
a := o.GetAnnotations() | ||
if a == nil { | ||
a = make(map[string]string) | ||
} | ||
AddTraceAnnotation(ctx, a) | ||
o.SetAnnotations(a) | ||
} | ||
|
||
return nil | ||
} | ||
|
||
// AddTraceAnnotationToObject - if there is a span for the current context, and | ||
// the object doesn't already have one set, adds it as an annotation | ||
func AddTraceAnnotationToObject(ctx context.Context, obj runtime.Object) error { | ||
m, err := meta.Accessor(obj) | ||
if err != nil { | ||
return err | ||
} | ||
annotations := m.GetAnnotations() | ||
if annotations == nil { | ||
annotations = make(map[string]string) | ||
} else { | ||
// Check if the object already has some context set. | ||
for _, key := range global.TextMapPropagator().Fields() { | ||
if annotationsCarrier(annotations).Get(key) != "" { | ||
return nil // Don't override | ||
} | ||
} | ||
} | ||
AddTraceAnnotation(ctx, annotations) | ||
m.SetAnnotations(annotations) | ||
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,45 @@ | ||
package tracing | ||
|
||
import ( | ||
"context" | ||
"log" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"go.opentelemetry.io/otel/api/global" | ||
"go.opentelemetry.io/otel/api/trace" | ||
corev1 "k8s.io/api/core/v1" | ||
) | ||
|
||
func TestInjectExtract(t *testing.T) { | ||
tracingCloser, err := SetupOTLP("some-controller") | ||
if err != nil { | ||
log.Fatalf("failed to set up Jaeger: %v", err) | ||
} | ||
defer tracingCloser.Close() | ||
|
||
var testNode corev1.Node | ||
ctx, sp := global.Tracer("test").Start(context.Background(), "foo") | ||
|
||
err = AddTraceAnnotationToObject(ctx, &testNode) | ||
assert.NoError(t, err) | ||
{ | ||
ctx := spanContextFromAnnotations(context.Background(), testNode.Annotations) | ||
assert.NoError(t, err) | ||
sc := trace.RemoteSpanContextFromContext(ctx) | ||
assert.Equal(t, sp.SpanContext(), sc) | ||
} | ||
|
||
// Check that adding a different span leaves the original in place | ||
ctx, sp2 := global.Tracer("test").Start(ctx, "bar") | ||
|
||
err = AddTraceAnnotationToObject(ctx, &testNode) | ||
assert.NoError(t, err) | ||
{ | ||
ctx := spanContextFromAnnotations(context.Background(), testNode.Annotations) | ||
assert.NoError(t, err) | ||
sc := trace.RemoteSpanContextFromContext(ctx) | ||
assert.Equal(t, sp.SpanContext(), sc) | ||
assert.NotEqual(t, sp2.SpanContext(), sc) | ||
} | ||
} |
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,39 @@ | ||
package tracing | ||
|
||
import ( | ||
"io" | ||
|
||
"go.opentelemetry.io/otel/api/global" | ||
"go.opentelemetry.io/otel/exporters/trace/jaeger" | ||
"go.opentelemetry.io/otel/propagators" | ||
sdktrace "go.opentelemetry.io/otel/sdk/trace" | ||
) | ||
|
||
// SetupJaeger sets up Jaeger with some defaults | ||
func SetupJaeger(serviceName string) (io.Closer, error) { | ||
// Create and install Jaeger export pipeline | ||
flush, err := jaeger.InstallNewPipeline( | ||
jaeger.WithCollectorEndpoint("http://jaeger-agent.default:14268/api/traces"), // FIXME name? | ||
jaeger.WithProcess(jaeger.Process{ | ||
ServiceName: serviceName, | ||
}), | ||
jaeger.WithSDK(&sdktrace.Config{DefaultSampler: sdktrace.AlwaysSample()}), | ||
) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
// set global propagator to tracecontext (the default is no-op). | ||
global.SetTextMapPropagator(propagators.TraceContext{}) | ||
|
||
return funcCloser{f: flush}, nil | ||
} | ||
|
||
type funcCloser struct { | ||
f func() | ||
} | ||
|
||
func (c funcCloser) Close() error { | ||
c.f() | ||
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,56 @@ | ||
package tracing | ||
|
||
import ( | ||
"context" | ||
|
||
"github.com/go-logr/logr" | ||
"go.opentelemetry.io/otel/api/trace" | ||
"go.opentelemetry.io/otel/label" | ||
) | ||
|
||
type tracingLogger struct { | ||
logr.Logger | ||
trace.Span | ||
} | ||
|
||
func (t tracingLogger) Enabled() bool { | ||
return t.Logger.Enabled() | ||
} | ||
|
||
func (t tracingLogger) Info(msg string, keysAndValues ...interface{}) { | ||
t.Logger.Info(msg, keysAndValues...) | ||
t.Span.AddEvent(context.Background(), "info", keyValues(keysAndValues...)...) | ||
} | ||
|
||
func (t tracingLogger) Error(err error, msg string, keysAndValues ...interface{}) { | ||
t.Logger.Error(err, msg, keysAndValues...) | ||
kvs := append([]label.KeyValue{label.String("message", msg)}, keyValues(keysAndValues...)...) | ||
t.Span.AddEvent(context.Background(), "error", kvs...) | ||
t.Span.RecordError(context.Background(), err) | ||
} | ||
|
||
func (t tracingLogger) V(level int) logr.Logger { | ||
return tracingLogger{Logger: t.Logger.V(level), Span: t.Span} | ||
} | ||
|
||
func keyValues(keysAndValues ...interface{}) []label.KeyValue { | ||
attrs := make([]label.KeyValue, 0, len(keysAndValues)/2) | ||
for i := 0; i+1 < len(keysAndValues); i += 2 { | ||
key, ok := keysAndValues[i].(string) | ||
if !ok { | ||
key = "non-string" | ||
} | ||
attrs = append(attrs, label.Any(key, keysAndValues[i+1])) | ||
} | ||
return attrs | ||
} | ||
|
||
func (t tracingLogger) WithValues(keysAndValues ...interface{}) logr.Logger { | ||
t.Span.SetAttributes(keyValues(keysAndValues...)...) | ||
return tracingLogger{Logger: t.Logger.WithValues(keysAndValues...), Span: t.Span} | ||
} | ||
|
||
func (t tracingLogger) WithName(name string) logr.Logger { | ||
t.Span.SetAttributes(label.String("name", name)) | ||
return tracingLogger{Logger: t.Logger.WithName(name), Span: t.Span} | ||
} |
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,46 @@ | ||
package tracing | ||
|
||
import ( | ||
"context" | ||
"io" | ||
|
||
"go.opentelemetry.io/otel/api/global" | ||
"go.opentelemetry.io/otel/exporters/otlp" | ||
"go.opentelemetry.io/otel/propagators" | ||
"go.opentelemetry.io/otel/sdk/resource" | ||
sdktrace "go.opentelemetry.io/otel/sdk/trace" | ||
"go.opentelemetry.io/otel/semconv" | ||
) | ||
|
||
// SetupOTLP sets up a global trace provider sending to OpenTelemetry with some defaults | ||
func SetupOTLP(serviceName string) (io.Closer, error) { | ||
exp, err := otlp.NewExporter( | ||
otlp.WithInsecure(), | ||
otlp.WithAddress("otlp-collector.default:55680"), | ||
) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
bsp := sdktrace.NewBatchSpanProcessor(exp) | ||
tracerProvider := sdktrace.NewTracerProvider( | ||
sdktrace.WithResource(resource.New(semconv.ServiceNameKey.String(serviceName))), | ||
sdktrace.WithSpanProcessor(bsp), | ||
) | ||
|
||
// set global propagator to tracecontext (the default is no-op). | ||
global.SetTextMapPropagator(propagators.TraceContext{}) | ||
global.SetTracerProvider(tracerProvider) | ||
|
||
return otlpCloser{exp: exp, bsp: bsp}, nil | ||
} | ||
|
||
type otlpCloser struct { | ||
exp *otlp.Exporter | ||
bsp *sdktrace.BatchSpanProcessor | ||
} | ||
|
||
func (s otlpCloser) Close() error { | ||
s.bsp.Shutdown() // shutdown the processor | ||
return s.exp.Shutdown(context.Background()) | ||
} |
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.
Should we allow to specify the endpoint? (parameter/env variable/other?)