apm-agent-php icon indicating copy to clipboard operation
apm-agent-php copied to clipboard

Distributed tracing by CLI scripts

Open bram123 opened this issue 1 year ago • 1 comments

Is your feature request related to a problem? Please describe. We would like to add distributed tracing to CLI scripts. We have a scheduler process that starts separate PHP processes. This scheduler reports back runtime status among other things. It would be great if we can pass the traceId + transactionId of the scheduler script, to the new PHP processes. Where it would be set as traceId + parentId.

Describe the solution you'd like The extension not only looks for request headers, but also for an ENV var. This way we can pass the tracecontext of the scheduler script to the new spawned processes.

bram123 avatar Mar 18 '24 17:03 bram123

I finally came back to this to see it was actually working as expected - at least for my case.

We can see here https://github.com/elastic/apm-agent-php/blob/0633e45f3589e2192179ae4806e74029d93d8fcb/agent/php/ElasticApm/Impl/AutoInstrument/TransactionForExtensionRequest.php#L618 that the code is looking up TRACEPARENT header from $_SERVER. Here https://github.com/elastic/apm-agent-php/blob/0633e45f3589e2192179ae4806e74029d93d8fcb/agent/php/ElasticApm/Impl/AutoInstrument/TransactionForExtensionRequest.php#L634 and here https://github.com/elastic/apm-agent-php/blob/0633e45f3589e2192179ae4806e74029d93d8fcb/agent/php/ElasticApm/Impl/AutoInstrument/TransactionForExtensionRequest.php#L481.

So in our scheduler (written in Go) we compute the distributed tracing value and pass it to the child process like this:

cmd := exec.Command(entrypoint, s.Arguments...)
cmd.Env = os.Environ()
c := tx.TraceContext()
c.Options = c.Options.WithRecorded(true)
tp := fmt.Sprintf("%02x-%032x-%016x-%02x", 0, c.Trace[:], c.Span[:], c.Options)
cmd.Env = append(cmd.Env, "TRACEPARENT="+tp, "HTTP_TRACEPARENT="+tp)

PHP will read the HTTP_TRACEPARENT value.

Now, I know this is a workaround, but it does what I need...

zobo avatar Jan 17 '25 10:01 zobo