gitlab.com/gitlab-org/labkit@v1.21.0/tracing/env_extractor.go (about) 1 package tracing 2 3 import ( 4 "context" 5 "os" 6 "strings" 7 8 opentracing "github.com/opentracing/opentracing-go" 9 "github.com/opentracing/opentracing-go/ext" 10 "gitlab.com/gitlab-org/labkit/correlation" 11 ) 12 13 // ExtractFromEnv will extract a span from the environment after it has been passed in 14 // from the parent process. Returns a new context, and a defer'able function, which 15 // should be called on process termination. 16 func ExtractFromEnv(ctx context.Context, opts ...ExtractFromEnvOption) (context.Context, func()) { 17 /* config not yet used */ applyExtractFromEnvOptions(opts) 18 tracer := opentracing.GlobalTracer() 19 20 // Extract the Correlation-ID 21 envMap := environAsMap(os.Environ()) 22 correlationID := envMap[envCorrelationIDKey] 23 if correlationID != "" { 24 ctx = correlation.ContextWithCorrelation(ctx, correlationID) 25 } 26 27 // Attempt to deserialize tracing identifiers 28 wireContext, err := tracer.Extract( 29 opentracing.TextMap, 30 opentracing.TextMapCarrier(envMap)) 31 32 if err != nil { 33 /* Clients could send bad data, in which case we simply ignore it */ 34 return ctx, func() {} 35 } 36 37 // Create the span referring to the RPC client if available. 38 // If wireContext == nil, a root span will be created. 39 additionalStartSpanOpts := []opentracing.StartSpanOption{ 40 ext.RPCServerOption(wireContext), 41 } 42 43 if correlationID != "" { 44 additionalStartSpanOpts = append(additionalStartSpanOpts, opentracing.Tag{Key: "correlation_id", Value: correlationID}) 45 } 46 47 serverSpan := opentracing.StartSpan( 48 "execute", 49 additionalStartSpanOpts..., 50 ) 51 ctx = opentracing.ContextWithSpan(ctx, serverSpan) 52 53 return ctx, func() { serverSpan.Finish() } 54 } 55 56 func environAsMap(env []string) map[string]string { 57 envMap := make(map[string]string, len(env)) 58 for _, v := range env { 59 s := strings.SplitN(v, "=", 2) 60 envMap[s[0]] = s[1] 61 } 62 return envMap 63 }