Skip to content
2 changes: 0 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -305,7 +305,6 @@ func InitConfig(ctx context.Context, clients *shared.ClientFactory, rootCmd *cob
// Used by Logstash
// TODO(slackcontext) Consolidate storing SystemID to slackcontext
clients.Config.SystemID = systemID
// Used by OpenTracing
ctx = slackcontext.SetSystemID(ctx, systemID)
rootCmd.SetContext(ctx)
// Debug logging
Expand All @@ -318,7 +317,6 @@ func InitConfig(ctx context.Context, clients *shared.ClientFactory, rootCmd *cob
// Used by Logstash
// TODO(slackcontext) Consolidate storing ProjectID to slackcontext
clients.Config.ProjectID = projectID
// Used by OpenTracing
ctx = slackcontext.SetProjectID(ctx, projectID)
rootCmd.SetContext(ctx)
// Debug logging
Expand Down
36 changes: 7 additions & 29 deletions internal/slackcontext/slackcontext.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,49 +29,31 @@ package slackcontext
import (
"context"

"github.com/opentracing/opentracing-go"
"github.com/slackapi/slack-cli/internal/slackerror"
"github.com/slackapi/slack-cli/internal/version"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
)

// contextKey is an unexported type to avoid context key collisions.
// Learn more: https://github.com/golang/net/blob/236b8f043b920452504e263bc21d354427127473/context/context.go#L100
type contextKey int

const (
contextKeyOpenTracingTracer contextKey = iota
contextKeyProjectID
contextKeyProjectID contextKey = iota
contextKeySessionID
contextKeySystemID
contextKeyTraceID
contextKeyVersion
)

// SetOpenTracingSpan returns a new `context.Context` that holds a reference to
// the span. If span is nil, a new context without an active span is returned.
func SetOpenTracingSpan(ctx context.Context, span opentracing.Span) context.Context {
ctx = opentracing.ContextWithSpan(ctx, span)
return ctx
}

// SetOpenTracingSpan returns a new `context.Context` that holds a reference to
// the `opentracing.Tracer`. If tracer is nil, a new context without a tracer returned.
func SetOpenTracingTracer(ctx context.Context, tracer opentracing.Tracer) context.Context {
ctx = context.WithValue(ctx, contextKeyOpenTracingTracer, tracer)
return ctx
}

// SetProjectID returns a new `context.Context` that holds a reference to
// the `projectID` and updates the `opentracing.Span` tag with the `projectID`.
// the `projectID` and sets the `project_id` attribute on the span in `ctx`.
func SetProjectID(ctx context.Context, projectID string) context.Context {
// Set projectID in the context
ctx = context.WithValue(ctx, contextKeyProjectID, projectID)

// Set projectID in OpenTracing by extracting the span and updating the tag
if span := opentracing.SpanFromContext(ctx); span != nil {
span.SetTag("project_id", projectID)
ctx = opentracing.ContextWithSpan(ctx, span)
}
trace.SpanFromContext(ctx).SetAttributes(attribute.String("project_id", projectID))

return ctx
}
Expand All @@ -95,16 +77,12 @@ func SetSessionID(ctx context.Context, sessionID string) context.Context {
}

// SetSystemID returns a new `context.Context` that holds a reference to
// the `systemID` and updates the `opentracing.Span` tag with the `systemID`.
// the `systemID` and sets the `system_id` attribute on the span in `ctx`.
func SetSystemID(ctx context.Context, systemID string) context.Context {
// Set systemID in the context
ctx = context.WithValue(ctx, contextKeySystemID, systemID)

// Set projectID in OpenTracing by extracting the span and updating the tag
if span := opentracing.SpanFromContext(ctx); span != nil {
span.SetTag("system_id", systemID)
ctx = opentracing.ContextWithSpan(ctx, span)
}
trace.SpanFromContext(ctx).SetAttributes(attribute.String("system_id", systemID))

return ctx
}
Expand Down
53 changes: 11 additions & 42 deletions internal/slackcontext/slackcontext_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,51 +19,14 @@ import (
"testing"

"github.com/google/uuid"
"github.com/opentracing/opentracing-go"
"github.com/slackapi/slack-cli/internal/slackerror"
"github.com/slackapi/slack-cli/internal/tracer"
"github.com/slackapi/slack-cli/internal/version"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/otel/attribute"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
)

func Test_SlackContext_SetOpenTracingSpan(t *testing.T) {
tests := map[string]struct {
expectedSpan opentracing.Span
}{
"sets the span in the context": {
expectedSpan: opentracing.StartSpan("test.span"),
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := t.Context()
ctx = SetOpenTracingSpan(ctx, tc.expectedSpan)
actualSpan := opentracing.SpanFromContext(ctx)
require.Equal(t, tc.expectedSpan, actualSpan)
})
}
}

func Test_SlackContext_SetOpenTracingTracer(t *testing.T) {
_, _tracer := tracer.SetupTracer(true)

tests := map[string]struct {
expectedTracer opentracing.Tracer
}{
"sets the Tracer in the context": {
expectedTracer: _tracer,
},
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := t.Context()
ctx = SetOpenTracingTracer(ctx, tc.expectedTracer)
actualTracer := ctx.Value(contextKeyOpenTracingTracer).(opentracing.Tracer)
require.Equal(t, tc.expectedTracer, actualTracer)
})
}
}

func Test_SlackContext_SetProjectID(t *testing.T) {
tests := map[string]struct {
expectedProjectID string
Expand All @@ -74,8 +37,11 @@ func Test_SlackContext_SetProjectID(t *testing.T) {
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := t.Context()
recorder := tracetest.NewSpanRecorder()
ctx, span := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)).Tracer("test").Start(t.Context(), "span")
ctx = SetProjectID(ctx, tc.expectedProjectID)
span.End()
require.Contains(t, recorder.Ended()[0].Attributes(), attribute.String("project_id", tc.expectedProjectID))
actualProjectID := ctx.Value(contextKeyProjectID).(string)
require.Equal(t, tc.expectedProjectID, actualProjectID)
})
Expand Down Expand Up @@ -135,8 +101,11 @@ func Test_SlackContext_SetSystemID(t *testing.T) {
}
for name, tc := range tests {
t.Run(name, func(t *testing.T) {
ctx := t.Context()
recorder := tracetest.NewSpanRecorder()
ctx, span := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)).Tracer("test").Start(t.Context(), "span")
ctx = SetSystemID(ctx, tc.expectedSystemID)
span.End()
require.Contains(t, recorder.Ended()[0].Attributes(), attribute.String("system_id", tc.expectedSystemID))
actualSystemID := ctx.Value(contextKeySystemID).(string)
require.Equal(t, tc.expectedSystemID, actualSystemID)
})
Expand Down
13 changes: 2 additions & 11 deletions internal/tracer/tracer.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ import (
)

// SetupTracer sets up the tracer to send data to honeycomb with OpenTelemetry
func SetupTracer(isDev bool) (io.Closer, opentracing.Tracer) {
func SetupTracer(isDev bool) io.Closer {
var collectorEndpoint = "https://slackb.com/traces/v1/otlp"
if isDev {
collectorEndpoint = "https://dev.slackb.com/traces/v1/otlp"
Expand All @@ -60,7 +60,7 @@ func SetupTracer(isDev bool) (io.Closer, opentracing.Tracer) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return provider.Shutdown(ctx)
}), bridge
})
}

func newTracerProvider(getenv func(string) string, newExporter func() (sdktrace.SpanExporter, error)) (*sdktrace.TracerProvider, error) {
Expand Down Expand Up @@ -173,15 +173,6 @@ func SetTraceHeaders(ctx context.Context, header http.Header) {
header.Set("x-b3-sampled", "0")
}

// TraceID returns the trace ID of span, or "" if span has no trace ID.
func TraceID(span opentracing.Span) string {
carrier := opentracing.HTTPHeadersCarrier(http.Header{})
if err := span.Tracer().Inject(span.Context(), opentracing.HTTPHeaders, carrier); err != nil {
return ""
}
return http.Header(carrier).Get("x-b3-traceid")
}

var (
flushMu sync.Mutex
flushFunc func()
Expand Down
24 changes: 14 additions & 10 deletions internal/tracer/tracer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -168,15 +168,19 @@ func Test_Start(t *testing.T) {
require.Len(t, spans, 3)
assert.Equal(t, spans["opentracing-parent"].SpanContext().SpanID(), spans["otel-child"].Parent().SpanID())
assert.Equal(t, spans["otel-child"].SpanContext().SpanID(), spans["opentracing-grandchild"].Parent().SpanID())
}

func Test_TraceID(t *testing.T) {
recorder := tracetest.NewSpanRecorder()
tracer := newBridgeTracer(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)))
span := tracer.StartSpan("span")
traceID := TraceID(span)
span.Finish()
assert.Len(t, traceID, 32)
assert.Equal(t, recorder.Ended()[0].SpanContext().TraceID().String(), traceID)
assert.Empty(t, TraceID(opentracing.NoopTracer{}.StartSpan("noop")))
recorder = tracetest.NewSpanRecorder()
tracer = newBridgeTracer(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(recorder)))
opentracing.SetGlobalTracer(tracer)
ctx, root := Start(context.Background(), "otel-root")
child2, _ := opentracing.StartSpanFromContext(ctx, "opentracing-child")
child2.Finish()
root.End()
spans = map[string]sdktrace.ReadOnlySpan{}
for _, span := range recorder.Ended() {
spans[span.Name()] = span
}
require.Len(t, spans, 2)
assert.False(t, spans["otel-root"].Parent().IsValid())
assert.Equal(t, spans["otel-root"].SpanContext().SpanID(), spans["opentracing-child"].Parent().SpanID())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💯 praise: Checking that an OpenTracing child of a parentless OpenTelemetry root still nests under it covers the riskiest part of this switch.

}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧪 suggestion (non-blocking): Test_Start always begins with an OpenTracing parent, but main now starts an OpenTelemetry root with no parent. Could we add that case, a Start root with an opentracing.StartSpanFromContext child, to pin the nesting the cmd/ spans rely on?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added in commit d774ebb, great catch! Test_Start now also starts an OpenTelemetry root with no parent and checks an opentracing.StartSpanFromContext child nests under it 🙇

30 changes: 15 additions & 15 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"strings"

"github.com/google/uuid"
"github.com/opentracing/opentracing-go"
"github.com/slackapi/slack-cli/cmd"
"github.com/slackapi/slack-cli/internal/goutils"
"github.com/slackapi/slack-cli/internal/iostreams"
Expand All @@ -31,6 +30,7 @@ import (
"github.com/slackapi/slack-cli/internal/tracer"
"github.com/slackapi/slack-cli/internal/useragent"
"github.com/slackapi/slack-cli/internal/version"
"go.opentelemetry.io/otel/attribute"
)

func main() {
Expand All @@ -43,8 +43,8 @@ func main() {
// - This would allow us to choose the correct API host based on flags
// - Uncomment `isDevTarget` if we refactor to cmd/root.go and update to call `ResolveAPIHost`
// var isDevTarget = shared.NewClientFactory().AuthClient().UserDefaultAuthIsProd(ctx) // TODO - hack, remove shared.clients
var jaegerCloser, jaegerTracer = tracer.SetupTracer(false) // Always setup open tracing on prod
ctx = slackcontext.SetOpenTracingTracer(ctx, jaegerTracer)
isDevTarget := false
traceCloser := tracer.SetupTracer(isDevTarget)

// Set context values
sessionID := uuid.New().String()
Expand All @@ -55,30 +55,30 @@ func main() {
osStr := os.Args[0:]
processName := goutils.RedactPII(strings.Join(osStr, " "))

var span = jaegerTracer.StartSpan("main", opentracing.Tag{Key: "version", Value: cliVersion})
span.SetTag("slack_cli_sessionID", sessionID)
span.SetTag("hashed_hostname", ioutils.GetHostname())
span.SetTag("slack_cli_process", processName)
ctx, span := tracer.Start(ctx, "main")
span.SetAttributes(
attribute.String("version", cliVersion),
attribute.String("slack_cli_sessionID", sessionID),
attribute.String("hashed_hostname", ioutils.GetHostname()),
attribute.String("slack_cli_process", processName),
)
if aiAgentName := useragent.GetAIAgentName(); aiAgentName != "" {
span.SetTag("ai_agent", aiAgentName)
span.SetAttributes(attribute.String("ai_agent", aiAgentName))
}
// system_id is set in root.go initConfig()
// project_id is set in root.go initConfig()

if traceID := tracer.TraceID(span); traceID != "" {
ctx = slackcontext.SetTraceID(ctx, traceID)
if spanContext := span.SpanContext(); spanContext.IsValid() {
ctx = slackcontext.SetTraceID(ctx, spanContext.TraceID().String())
}

// Flush on return here, and before each exit in cmd/root.go, which skips these defers
tracer.SetFlush(func() {
span.Finish()
_ = jaegerCloser.Close()
span.End()
_ = traceCloser.Close()
})
defer tracer.Flush()

// add root span to context
ctx = slackcontext.SetOpenTracingSpan(ctx, span)

rootCmd, clients := cmd.Init(ctx)
cmd.ExecuteContext(ctx, rootCmd, clients)
}
Expand Down
Loading