go.undefinedlabs.com/scopeagent@v0.4.2/instrumentation/process/cmd.go (about) 1 package process 2 3 import ( 4 "context" 5 "os/exec" 6 "path/filepath" 7 "strings" 8 9 "github.com/opentracing/opentracing-go" 10 11 "go.undefinedlabs.com/scopeagent/instrumentation" 12 scopetracer "go.undefinedlabs.com/scopeagent/tracer" 13 ) 14 15 // Injects the span context to the command environment variables 16 func InjectToCmd(ctx context.Context, command *exec.Cmd) *exec.Cmd { 17 if command.Env == nil { 18 command.Env = []string{} 19 } 20 err := InjectFromContext(ctx, &command.Env) 21 if err != nil { 22 instrumentation.Logger().Println(err) 23 } 24 return command 25 } 26 27 // Injects a new span context to the command environment variables 28 func InjectToCmdWithSpan(ctx context.Context, command *exec.Cmd) (opentracing.Span, context.Context) { 29 innerSpan, innerCtx := opentracing.StartSpanFromContextWithTracer(ctx, instrumentation.Tracer(), 30 "Exec: "+getOperationNameFromArgs(command.Args)) 31 if sp, ok := innerSpan.(scopetracer.Span); ok { 32 sp.UnsafeSetTag("Args", command.Args) 33 } else { 34 innerSpan.SetTag("Args", command.Args) 35 } 36 innerSpan.SetTag("Path", command.Path) 37 innerSpan.SetTag("Dir", command.Dir) 38 InjectToCmd(innerCtx, command) 39 return innerSpan, innerCtx 40 } 41 42 func getOperationNameFromArgs(args []string) string { 43 if args == nil || len(args) == 0 { 44 return "" 45 } 46 var operationNameBuilder = new(strings.Builder) 47 operationNameBuilder.WriteString(filepath.Base(args[0])) 48 operationNameBuilder.WriteRune(' ') 49 for _, item := range args[1:] { 50 if strings.ContainsRune(item, ' ') { 51 operationNameBuilder.WriteRune('"') 52 operationNameBuilder.WriteString(item) 53 operationNameBuilder.WriteRune('"') 54 } else { 55 operationNameBuilder.WriteString(item) 56 } 57 operationNameBuilder.WriteRune(' ') 58 } 59 return operationNameBuilder.String() 60 }