Skip to content

[tracing] Flush spans on --run_once, and bound the flush - #1494

Merged
manugarg merged 6 commits into
mainfrom
tracing-run-once-flush
Sep 22, 2026
Merged

manugarg merged 6 commits into
mainfrom
tracing-run-once-flush

Conversation

@manugarg

@manugarg manugarg commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Follow-up to #1358.

--run_once never flushed spans

tracing.Init returns tp.Shutdown for a batching provider, and the only
caller was the ctx.Done() goroutine in Start(). --run_once returns from
main without ever calling Start, so every span from a single run was
dropped.

This adds an exported cloudprober.Shutdown() and calls it from main's
run_once branch. It's an explicit call before the error check, not a
defer after Init(): l.Criticalf exits the process without running
defers, and a failing probe is exactly the case where you want its spans.

Bounding the flush

All shutdown call sites go through a shared shutdownTracing() helper with a
3s timeout. The init rollback path previously used context.Background()
while holding the write lock, so an unreachable collector (which the exporter
retries with a backoff) could hold up initialization. And 3s keeps the flush
below the default stop_time_sec of 5s: at 5s the flush deadline and main's
os.Exit(0) expired at the same instant, so the "Error shutting down tracing"
warning was unreachable in practice.

Shutdown() is the one teardown path, and it's one-way

Start()'s ctx.Done() goroutine used to do its own cleanup, overlapping
with what Shutdown() needed to do. The whole teardown now lives in
Shutdown() -- default servers, probes, init context, tracing flush -- and
the goroutine is just <-ctx.Done(); Shutdown(). Start() runs the prober on
a context derived from the caller's, so Shutdown() can stop the probes even
when the caller's context is still live.

The RunOnce path consequently releases the default HTTP/gRPC listeners that
Init opens for it, which embedders calling Init + RunOnce had no way to
do before.

Everything Init acquires lives in one instance struct, so a shutdown swaps
in a zero value rather than clearing fields one at a time.

Behavior change: cloudprober can be initialized only once

Shutdown() is one-way, and Init now panics if it's called a second
time, whether or not a shutdown has happened (it used to silently return
nil when already initialized). Cloudprober is a process-wide singleton and
we don't restart it; config reload will reload individual components rather
than the whole prober.

This drops TestRestart, added in a905e2c (2021) so embedders could stand up
a full cloudprober per test case. What it actually verified -- that a teardown
gives the ports back -- is now covered by TestShutdownWithoutStart and
TestShutdownStopsStartedProber.

RunOnce also returns an error instead of panicking when the prober isn't
initialized, which covers calling it before Init as well.

Verification

Against a fake OTLP/HTTP collector:

  • --run_once, pre-change binary: no export at all; with the change: spans
    exported, on both the success path and the probe-failure path that ends in
    Criticalf.
  • the Start path still flushes on SIGTERM.
  • black-holed collector (240.0.0.1:4318): run exits in 3.1s with
    WARN Error shutting down tracing err="context deadline exceeded".

Tests cover the flush (nil, once-only, deadline, error), teardown without
Start, teardown of a started prober including that its ports come back, and
the init-after-shutdown panic. go test -race is clean.

Not in this change

A stop_time_sec: 0 config installs no signal handler in main at all, so
SIGTERM kills the process with spans unflushed. That's a separate fix.

Tracing's shutdown func, which flushes buffered spans, was only called from
Start()'s ctx.Done() goroutine. The --run_once path never calls Start, so
spans from a single run were always dropped.

Add an exported cloudprober.Shutdown() and call it from main's run_once
branch. It's called before the error check, as l.Criticalf exits without
running defers, and a failing probe is exactly when you want its spans.
Shutdown() is not needed by Start() users (canceling Start's context does the
same cleanup), and since tp.Shutdown is terminal, embedders that call RunOnce
repeatedly should call it only once, on the way out.

While here, route all three shutdown call sites -- the init rollback, Start's
goroutine, and Shutdown() -- through a shared shutdownTracing() helper with a
3s timeout. The rollback path previously used context.Background(), so an
unreachable collector, which the exporter retries with a backoff, could hold
up initialization while holding the write lock. The 3s budget also keeps the
flush below the default stop_time_sec of 5s, so the "Error shutting down
tracing" warning is now actually reachable before main's os.Exit(0).
Start()'s ctx.Done() goroutine and Shutdown() were doing overlapping
cleanup, with only the tracing flush in common. Move the whole teardown --
default servers, init context, tracing flush, and resetting the global state
-- into Shutdown(), and reduce the goroutine to waiting on the context and
calling it.

Besides removing the second cleanup path, this means the RunOnce path now
releases the default HTTP/gRPC listeners that Init opens for it, which
matters for embedders that call Init + RunOnce without ever calling Start.
It also removes a small race: the goroutine used to read cancelInitCtx and
tracingShutdown before taking the write lock.

Since Shutdown() is now terminal for the prober as well, RunOnce returns an
error instead of panicking when the prober isn't initialized. That also
covers calling RunOnce before Init, which panicked in prober.Run before.
@cbroglie

Copy link
Copy Markdown
Contributor

LGTM 👍

…g it

Two fixes from a review of the previous commit.

Shutdown() only canceled the init context, but the probes, sysvars and the
user-configured servers all run on the context passed to Start(). That was
fine while the teardown could only be reached by canceling that context, but
Shutdown() is exported now: an embedder could call it, get a nil'd prober and
still-running probes, and then have Init()+Start() succeed and start a second
set of them. Start() now runs the prober on a context it derives from the
caller's, and Shutdown() cancels it.

Shutdown() also took the write lock upfront and held it through the gRPC
server stop and the trace flush, which the code it replaced deliberately did
not do. With an unreachable collector that stalls every config/info reader,
including in-flight web handlers, for up to tracingShutdownTimeout. Snapshot
the fields under a read lock, tear down without the lock, and take the write
lock only to reset the state, as before.
…he next instance

Two more fixes from a review of the previous commit, both confirmed with
throwaway tests before and after.

Start()'s cleanup goroutine called the package-level Shutdown(), which reads
the globals when it wakes up rather than what Start captured. Since Shutdown()
itself cancels the start context, an explicit Shutdown() woke that goroutine,
and if the caller re-initialized in the meantime, the goroutine tore down the
new instance: Init(); Start(); Shutdown(); Init() left the fresh prober and
its listeners alive for ~500ms and then killed them. The goroutine now hands
the prober it was started for to an unexported shutdown(), which is a no-op
unless that prober is still the running one.

Shutdown() also snapshotted the fields under a read lock and cleared them only
at the end, so two shutdowns could both see non-nil state and tear everything
down twice -- with a 300ms tracing shutdown stub, Start() + Shutdown() ran it
twice, concurrently. Clear the state (and close the servers, which doesn't
block) while holding the write lock, and keep only the blocking work -- the
gRPC server stop and the span flush -- outside it.

Also drop two doc claims that don't hold: Shutdown() isn't a no-op when
there's nothing to clean up (it stops the default gRPC server either way,
including an embedder-installed one), and probes and user-configured servers
are only signaled, so they may still be going away when it returns.
Cloudprober is a process-wide singleton and we don't restart it, so the
machinery the previous commit grew to keep a second instance safe was
protecting a case that can't happen. Instead, say so in the code: Shutdown()
sets a one-way 'done' flag, and Init panics if it's called again, whether or
not a shutdown has happened.

That removes the need for all of it. The cleanup goroutine goes back to
calling Shutdown() directly, since it can't reach an instance it doesn't own.
Nothing can replace the resources once done is set, so the teardown reads them
without holding the lock, and the flag alone makes a second Shutdown a no-op.

Everything Init acquires now lives in one 'instance' struct embedded in the
global, so shutting down swaps in a zero value instead of clearing nine fields
one at a time, and initializing fills it in a single assignment. The two
state.SetDefault*(nil) calls are gone with it: their comment said they were
there to prevent reuse in tests, and reuse is exactly what we're outlawing.

TestRestart goes too -- it initialized cloudprober twice, which is now a panic.
It was added in a905e2c (2021) to let embedders stand up a full cloudprober
per test case; what it actually verified, that a teardown gives the ports back,
is now covered by TestShutdownWithoutStart and TestShutdownStopsStartedProber.
FakeSurfacer.Write selected between sending on its channel and a done
context, and with room left in the channel Go picks between the two at
random. TestShutdownStopsStartedProber reads "no more metrics" as the signal
that Shutdown stopped the prober, so a metric still buffered when the context
was canceled could be delivered anyway and fail the test. Check the context
first.
@manugarg
manugarg merged commit c6cb480 into main Sep 22, 2026
13 checks passed
@manugarg
manugarg deleted the tracing-run-once-flush branch September 25, 2026 07:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants