Repository navigation
[tracing] Flush spans on --run_once, and bound the flush - #1494
Merged
Merged
Conversation
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.
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up to #1358.
--run_oncenever flushed spanstracing.Initreturnstp.Shutdownfor a batching provider, and the onlycaller was the
ctx.Done()goroutine inStart().--run_oncereturns frommainwithout ever callingStart, so every span from a single run wasdropped.
This adds an exported
cloudprober.Shutdown()and calls it from main'srun_oncebranch. It's an explicit call before the error check, not adeferafterInit():l.Criticalfexits the process without runningdefers, 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 a3s 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_secof 5s: at 5s the flush deadline and main'sos.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-wayStart()'sctx.Done()goroutine used to do its own cleanup, overlappingwith what
Shutdown()needed to do. The whole teardown now lives inShutdown()-- default servers, probes, init context, tracing flush -- andthe goroutine is just
<-ctx.Done(); Shutdown().Start()runs the prober ona context derived from the caller's, so
Shutdown()can stop the probes evenwhen the caller's context is still live.
The RunOnce path consequently releases the default HTTP/gRPC listeners that
Initopens for it, which embedders callingInit+RunOncehad no way todo before.
Everything
Initacquires lives in oneinstancestruct, so a shutdown swapsin a zero value rather than clearing fields one at a time.
Behavior change: cloudprober can be initialized only once
Shutdown()is one-way, andInitnow panics if it's called a secondtime, whether or not a shutdown has happened (it used to silently return
nilwhen already initialized). Cloudprober is a process-wide singleton andwe 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 upa full cloudprober per test case. What it actually verified -- that a teardown
gives the ports back -- is now covered by
TestShutdownWithoutStartandTestShutdownStopsStartedProber.RunOncealso returns an error instead of panicking when the prober isn'tinitialized, which covers calling it before
Initas well.Verification
Against a fake OTLP/HTTP collector:
--run_once, pre-change binary: no export at all; with the change: spansexported, on both the success path and the probe-failure path that ends in
Criticalf.Startpath still flushes on SIGTERM.240.0.0.1:4318): run exits in 3.1s withWARN 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, andthe init-after-shutdown panic.
go test -raceis clean.Not in this change
A
stop_time_sec: 0config installs no signal handler inmainat all, soSIGTERM kills the process with spans unflushed. That's a separate fix.