Skip to content
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

#81 template traceparent into exec command args #308

Merged
merged 7 commits into from
Mar 11, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## [0.4.3] - 2024-02-23

Add injection of `{{traceparent}}` to `otel-cli exec`.

### Added

- `otel-cli exec echo {{traceparent}}` is now supported to pass traceparent to child process

## [0.4.2] - 2023-12-01

The Docker container now builds off `alpine:latest` instead of `scratch`. This
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ otel-cli exec --kind producer "otel-cli exec --kind consumer sleep 1"
# used by span and exec. use --tp-ignore-env to ignore it even when present
export TRACEPARENT=00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01

# you can pass the traceparent to a child via arguments as well
# {{traceparent}} in any of the command's arguments will be replaced with the traceparent string
otel-cli exec --name "curl api" -- \
curl -H 'traceparent: {{traceparent}}' https://myapi.com/v1/coolstuff

# create a span with a custom start/end time using either RFC3339,
# same with the nanosecond extension, or Unix epoch, with/without nanos
otel-cli span --start 2021-03-24T07:28:05.12345Z --end 2021-03-24T07:30:08.0001Z
Expand Down
52 changes: 31 additions & 21 deletions otelcli/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"time"

"github.com/equinix-labs/otel-cli/otlpclient"
"github.com/equinix-labs/otel-cli/w3c/traceparent"
"github.com/spf13/cobra"
tracev1 "go.opentelemetry.io/proto/otlp/trace/v1"
)
Expand Down Expand Up @@ -53,27 +54,52 @@ otel-cli exec -s "outer span" 'otel-cli exec -s "inner span" sleep 1'`,
func doExec(cmd *cobra.Command, args []string) {
ctx := cmd.Context()
config := getConfig(ctx)
span := config.NewProtobufSpan()

// put the command in the attributes, before creating the span so it gets picked up
config.Attributes["command"] = args[0]
config.Attributes["arguments"] = ""

// no deadline if there is no command timeout set
cancelCtxDeadline := func() {}
// fork the context for the command so its deadline doesn't impact the otlpclient ctx
cmdCtx := ctx
cmdTimeout := config.ParseExecCommandTimeout()
if cmdTimeout > 0 {
cmdCtx, cancelCtxDeadline = context.WithDeadline(ctx, time.Now().Add(cmdTimeout))
}

// pass the existing env but add the latest TRACEPARENT carrier so e.g.
// otel-cli exec 'otel-cli exec sleep 1' will relate the spans automatically
childEnv := []string{}

// set the traceparent to the current span to be available to the child process
var tp traceparent.Traceparent
if config.GetIsRecording() {
tp = otlpclient.TraceparentFromProtobufSpan(span, config.GetIsRecording())
childEnv = append(childEnv, fmt.Sprintf("TRACEPARENT=%s", tp.Encode()))
// when not recording, and a traceparent is available, pass it through
} else if !config.TraceparentIgnoreEnv {
tp := config.LoadTraceparent()
if tp.Initialized {
childEnv = append(childEnv, fmt.Sprintf("TRACEPARENT=%s", tp.Encode()))
}
}

var child *exec.Cmd
if len(args) > 1 {
tpArgs := make([]string, len(args)-1)
// loop over the args replacing {{traceparent}} with the current tp
for i, arg := range args[1:] {
tpArgs[i] = strings.Replace(arg, "{{traceparent}}", tp.Encode(), -1)
}

// CSV-join the arguments to send as an attribute
buf := bytes.NewBuffer([]byte{})
csv.NewWriter(buf).WriteAll([][]string{args[1:]})
csv.NewWriter(buf).WriteAll([][]string{tpArgs})
config.Attributes["arguments"] = buf.String()

child = exec.CommandContext(cmdCtx, args[0], args[1:]...)
child = exec.CommandContext(cmdCtx, args[0], tpArgs...)
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Should there be a command-line arg to enable/disable this feature?

} else {
child = exec.CommandContext(cmdCtx, args[0])
}
Expand All @@ -83,30 +109,13 @@ func doExec(cmd *cobra.Command, args []string) {
child.Stdout = os.Stdout
child.Stderr = os.Stderr

// pass the existing env but add the latest TRACEPARENT carrier so e.g.
// otel-cli exec 'otel-cli exec sleep 1' will relate the spans automatically
child.Env = []string{}

// grab everything BUT the TRACEPARENT envvar
for _, env := range os.Environ() {
if !strings.HasPrefix(env, "TRACEPARENT=") {
child.Env = append(child.Env, env)
}
}

span := config.NewProtobufSpan()

// set the traceparent to the current span to be available to the child process
if config.GetIsRecording() {
tp := otlpclient.TraceparentFromProtobufSpan(span, config.GetIsRecording())
child.Env = append(child.Env, fmt.Sprintf("TRACEPARENT=%s", tp.Encode()))
// when not recording, and a traceparent is available, pass it through
} else if !config.TraceparentIgnoreEnv {
tp := config.LoadTraceparent()
if tp.Initialized {
child.Env = append(child.Env, fmt.Sprintf("TRACEPARENT=%s", tp.Encode()))
childEnv = append(childEnv, env)
}
}
child.Env = childEnv

// ctrl-c (sigint) is forwarded to the child process
signals := make(chan os.Signal, 10)
Expand All @@ -119,6 +128,7 @@ func doExec(cmd *cobra.Command, args []string) {
close(signalsDone)
}()

span.StartTimeUnixNano = uint64(time.Now().UnixNano())
if err := child.Run(); err != nil {
span.Status = &tracev1.Status{
Message: fmt.Sprintf("exec command failed: %s", err),
Expand Down
Loading