Repository navigation
Conversation
|
❗ By default, the pull request is configured to backport to all release branches.
|
|
/test |
|
@armru, here's the link to the E2E on CNPG workflow run: https://github.com/cloudnative-pg/cloudnative-pg/actions/runs/30635557623 |
e1ef883 to
58f8150
Compare
|
/test |
|
@mnencia, here's the link to the E2E on CNPG workflow run: https://github.com/cloudnative-pg/cloudnative-pg/actions/runs/30824380404 |
|
/test |
|
@armru, here's the link to the E2E on CNPG workflow run: https://github.com/cloudnative-pg/cloudnative-pg/actions/runs/30827623746 |
|
/test |
|
@mnencia, here's the link to the E2E on CNPG workflow run: https://github.com/cloudnative-pg/cloudnative-pg/actions/runs/30887478132 |
|
/test |
|
@armru, here's the link to the E2E on CNPG workflow run: https://github.com/cloudnative-pg/cloudnative-pg/actions/runs/30931264640 |
|
/test |
|
@armru, here's the link to the E2E on CNPG workflow run: https://github.com/cloudnative-pg/cloudnative-pg/actions/runs/30989269854 |
a5efa4c to
74ae50f
Compare
The isolation check reported an isolated primary as not alive and left the shutdown to the kubelet. That arrives as an ordinary termination and is served with a smart shutdown, a mode that lets the sessions already open run to completion, so the primary went on acknowledging writes it could no longer replicate for as long as smartShutdownTimeout allowed. The probe now asks the instance manager to stop PostgreSQL once the isolation verdict has repeated as many times as the kubelet would have needed to kill the container. That shutdown departs from the demotion it shares a code path with in two ways, both because it has to end the writes rather than let the instance settle: it is bounded by a budget of its own rather than switchoverDelay, which is measured in hours, and it gives up the preceding checkpoint, which is unbounded and would only have shortened a recovery this instance pays anyway on the rewind ahead of it. Resolving that threshold means reading both the field that carries it and the older livenessProbeTimeout it is derived from, so the computation now lives on the Cluster and the pod spec uses it too. The check is also skipped while the instance is fenced, where there is no PostgreSQL to stop and a fenced instance should not be restarted over connectivity it can do nothing about. Closes #11280 Signed-off-by: Marco Nenciarini <[email protected]>
The liveness probe's internal counter and the kubelet's own failure threshold count to the same number from the same first failure, so the counter reaches its threshold on exactly the probe call that is also the kubelet's Nth failure. The handler used to spawn the shutdown request in a goroutine and then write the 500 that makes the kubelet send SIGTERM. The goroutine normally wins the race by an HTTP round trip, but nothing synchronised the two: if the lifecycle loop served the SIGTERM first, it ran the smart-then-fast shutdown path instead, bringing back the 180 second smart phase this branch exists to remove. Issue the request synchronously and bounded instead, before writing the response, and let the handler know whether the lifecycle manager took it up. There is room for this: the kubelet allows 5 seconds and the failing verdict has already spent one or two of them on the pinger. This also closes a second window the previous guard left open. The guard read StoppedBecauseIsolated(), a flag the lifecycle loop sets only once it starts handling the command, not when the probe issues it. Between issuing the request and the lifecycle loop taking it up, and for the whole duration of the shutdown that follows, that flag read false, so further failing probes could keep spawning goroutines parked on the unbuffered command channel. Claiming the right to issue the request on the probe side, under the same lock that reads the counter, closes that window instead. StoppedBecauseIsolated() stays on Instance for the lifecycle loop, which still needs it; the probe no longer uses it as its guard. Signed-off-by: Armando Ruocco <[email protected]>
The isolation counter had tests, but nothing called IsHealthy itself, so the fenced early return, the guard against a second request, the shutdown request handover, and every success path that resets the counter were untested. Build a real executor over a real instance and a real ClusterCache backed by a fake client, the same way cache_test.go already does, and drive IsHealthy through httptest. A cache primed with one successful fetch and then repointed at a name the fake client does not have reproduces the shape the cache is left in once the API server stops answering after having answered at least once, which is what an isolated primary sees. The test that matters most reads the instance's own command channel from a goroutine started before the call that is expected to reach the failure threshold, and asserts that a real value arrives on it. That is the scenario the previous commit's race lived in: a mock would have accepted the old, unsynchronised goroutine just as easily. Left out on purpose: asserting that SkipCheckpoint actually prevents tryCheckpointBeforeShutdown from running, and that the 30 second budget reaches pg_ctl's -t flag. Both need either a running PostgreSQL or a new seam in Shutdown, and introducing that seam is a refactor of code this branch only touched in passing. Signed-off-by: Armando Ruocco <[email protected]>
The previous wording presented the escalation from a fast to an immediate shutdown as the exception, a 30 second grace period that would normally be enough. On a primary with any real load, the opposite is true. pg_ctl does not kill anything when its own timeout runs out: it simply exits and leaves the postmaster running, which is why the instance manager has to escalate itself rather than rely on it. The shutdown checkpoint that PostgreSQL always runs before it can stop is CHECKPOINT_IMMEDIATE and has no time limit of its own, and skipping the explicit CHECKPOINT this path takes to save time only pushes the outstanding dirty-buffer work into that mandatory checkpoint instead of doing it ahead of time. On a busy primary with a sizeable shared_buffers, the 30 second budget routinely expires while that checkpoint is still running, and the immediate shutdown aborts it mid-flight. The instance still comes back up through crash recovery rather than a clean shutdown, and that costs nothing beyond what the instance was already going to pay on its next start, with no acknowledged commit lost either way, which is what the surrounding text already said and still says. Signed-off-by: Armando Ruocco <[email protected]>
The claim that keeps a second shutdown request from being issued was given back only when the handover itself failed, and it consumed the failure count when it was taken. Both left it able to outlast the episode it was taken for. A successful handover is not proof that PostgreSQL was asked to stop: the lifecycle loop discards anything but an unfencing request while the instance is fenced, so a fenceOn consumed just before leaves the isolation request dropped with the claim still held, and from then on every isolation was met with a probe failure and nothing more, for the life of the process and without a trace in the log. Give the claim back on any probe that finds the instance answering for itself again, which cannot interrupt a shutdown genuinely in flight because while one runs no success path is reached. Consuming the count was pointless and harmful in the same way. The claim is what bounds the requests to one at a time, so an outstanding claim already blocks every further one; the count restart it was there for was unreachable. Leaving the count standing makes the release exact, so a handover the kubelet cut short by cancelling the probe is retried on the next failure instead of costing a fresh run of the whole threshold. Signed-off-by: Marco Nenciarini <[email protected]>
The flag was set before the shutdown was attempted, and the error it can return was logged and dropped. A failure that is not a pg_ctl exit status never escalates to an immediate shutdown, so PostgreSQL can still be running with the instance already marked as stopped. Nothing clears the flag, and the lifecycle loop uses it to drop restart requests, so every later restart was silently ignored and its caller left waiting for a timeout. Set it after the shutdown reports success instead. The loop reads it when it observes the postmaster's exit, a later pass through its select than the one handling this request, so recording it there is still in time. Signed-off-by: Marco Nenciarini <[email protected]>
…ynchronous Delivery was asserted with Eventually, whose default second is far longer than the handover it is watching, so a request dispatched in the background and racing the kubelet's own signal satisfied it just as well. The test that was supposed to prove no second request is issued asserted nothing either: with a threshold of one and a reader that stops after the first command, a second request simply times out unnoticed on the unbuffered channel, which looks the same from outside as one the handler declined to issue. Drain the command channel for the whole spec instead of taking a single value, and add the case with no reader at all. That case is what separates a synchronous handover from a backgrounded one: the handler has to sit on the send until its own budget runs out, and it has to give the claim back so the next failing probe asks again. Signed-off-by: Marco Nenciarini <[email protected]>
…t closes it Promotion is governed by the primary lease, whose duration runs independently of whether the old primary has stopped, so the two can in principle overlap however promptly the isolated one is stopped. Little usually reaches it in that window, and synchronous replication removes what is left, but the section read as though stopping the instance were the whole of it. Signed-off-by: Marco Nenciarini <[email protected]>
RequestFastImmediateShutdownForIsolation has three ways out: the lifecycle manager takes the request, the 500ms timer fires, or the caller's context is cancelled. Only the first two had a spec; every existing one derives its context from context.Background(), so the third branch ran untested. That branch matters in practice: the probe handler receives a request-scoped context, so when the kubelet gives up on a probe mid handover, cancellation is exactly what tells the handler to stop waiting, report failure, and give the claim back so the next failing probe asks again instead of finding it stuck. Add a spec that cancels the context before the call, with nobody reading the command channel, and asserts the handler reports failure well inside the 500ms budget rather than waiting out the timer, then asserts a second call still gets a shutdown request through, proving the claim was released. Signed-off-by: Armando Ruocco <[email protected]>
The IsolationCheck field comment still described the pre-fix behaviour, where the check only observed the isolation and left stopping PostgreSQL to something else. Since the liveness handler now hands the isolated primary a fast shutdown itself, say so, so the generated API reference stops telling users the check merely makes the instance safe to shut down when it already shuts it down. Signed-off-by: Armando Ruocco <[email protected]>
self_fencing_test.go only asserted that the isolated primary's container eventually exits, which passes identically whether or not the fast shutdown handover actually runs: with no session open, a plain smart shutdown finishes at once and the bug this issue is about never surfaces at end-to-end scale. Open one long-lived psql backend against the primary before the partition and keep it committing through a loop running inside the container, reached through the host's Docker daemon rather than kubectl exec (that channel dies the instant the node disconnects, so it measures when the tunnel broke rather than when PostgreSQL stopped). Record the server's own clock_timestamp() on every acknowledged commit, and once the primary is confirmed isolated, assert the last one lands within a wide margin of the partition instead of drifting into the smart shutdown's default 180 second timeout. Signed-off-by: Armando Ruocco <[email protected]>
golangci-lint's line-length check flagged the It() description added for the cancelled-context handover spec. Shorten it to fit without changing what it covers. Signed-off-by: Armando Ruocco <[email protected]>
make manifests mirrors the same field comment into the CRD YAML, which the previous commit left stale. Signed-off-by: Armando Ruocco <[email protected]>
The last acknowledged commit keeps pace with the clock for as long as the primary answers, so reading it once measured little more than when the spec happened to reach that step: an instance still committing looked prompt if the promotion checks got there early. Wait for the writer to stop being answered first, then judge when it stopped, and make that check the one that runs before the container is expected to have exited. Signed-off-by: Armando Ruocco <[email protected]>
lastAcknowledged() stops advancing for six different reasons, and only one of them is the isolated primary actually falling silent: the host-side docker exec client dying, the crictl exec session ending, psql exiting, the in-container bash loop dying, the container being killed, or bufio.Scanner stopping on its own error. Nothing in the previous version told these apart, so the spec could pass while the channel measuring it had simply broken. A fast shutdown terminates open backends, so the psql session inside the container writes a diagnostic to stderr when this happens. Capture that stream and time its first line on the host clock: the assertion becomes that this line arrives before the staleness threshold, which is positive evidence the connection was open before the partition and was told to go away, rather than an inference drawn from quiet. The previous staleness check on the last acknowledged commit stays as a secondary assertion, now expressed against the stderr arrival time instead of the host clock directly, since it still catches a channel that keeps producing commits after the primary was supposed to be down. The command's exit status, both scanners' errors, and the captured stderr lines are now recorded and printed to GinkgoWriter, so a broken channel in a nightly run leaves something to read. Signed-off-by: Armando Ruocco <[email protected]>
The stderr arrival time was latched by the first line the writer process ever produced, whichever stream event caused it. Anything on that stream before the partition, a psql error from a loop that started badly or a docker or crictl warning, put the arrival time before the disconnection, and an arrival before the partition trivially satisfies a check looking for one that lands soon after it. The writer now learns when the node was disconnected and only latches lines that arrive afterwards, keeping the earlier ones for the diagnostics report. The check on the last acknowledged commit was read once, the instant the termination line landed, and compared against that same line's arrival time. Read at that moment it could only ever describe commits that had already happened, and comparing two arrival times directly put it on a knife edge: both streams are drained by their own goroutine and stamped when a line is read, so a commit written a fraction of a millisecond before the termination line can be read after it. It now watches the counter over a few seconds with a one second tolerance, which is what it was always meant to say: nothing may still be acknowledging writes once the connection has reported it is gone. Signed-off-by: Armando Ruocco <[email protected]>
74ae50f to
57147ab
Compare
|
Closing as partially superseded by #11357 |
|
❗ By default, the pull request is configured to backport to all release branches.
|
The isolation check only failed the liveness probe, leaving the shutdown to the kubelet's ordinary termination path. That is a smart shutdown: it lets already-open sessions keep committing for up to smartShutdownTimeout (180s default), while a replacement primary may already be promoting. On the first isolation failure, request an immediate shutdown of PostgreSQL directly, instead of waiting for the kubelet's SIGTERM. Immediate shutdown skips the checkpoint and the fast phase, so nothing delays it. The instance is already headed for a rewind, so the crash recovery this costs on the next start is free. Reuses the non-blocking request PR #11347 added for the same reason, a primary that can't be trusted to shut down cleanly. Firing on the first failure, rather than matching the kubelet's own failureThreshold, means a transient blip a retry would have cleared can trigger a shutdown too. Accepted trade-off: a truly isolated primary should stop immediately. This does not order detection against replica promotion. Detection follows the kubelet's probe cadence; promotion follows the primary lease's LeaseDuration on branches that have one (1.30+), with no time floor at all on branches that don't (1.28/1.29). At the defaults the two are roughly a tie, not a guaranteed order. Only PR #11357 closes that gap, by detecting isolation off the lease's own renewal clock instead of the probe. PR #11283 took the same approach as this patch. It was closed as partially superseded by #11357 on main. This is a backport-sized version for the release branches #11357 won't reach. Closes #11280 Signed-off-by: Marco Nenciarini <[email protected]>
The primary isolation check is documented as stopping an isolated primary from
accepting writes, but it only returned HTTP 500 from the liveness probe. The
kubelet then signalled the container, and the instance manager handled that
signal the way it handles a planned termination, with
pg_ctl stop -m smart. Asmart shutdown refuses new connections but never signals the backends that are
already open, so every session established before the partition kept committing
on the isolated primary for as long as
.spec.smartShutdownTimeoutallowed,180 seconds by default, while a replacement primary was already acknowledging
writes elsewhere.
The isolation path now asks for the shutdown itself instead of relying on the
kubelet's timing. When the instance is found isolated as many times in a row as
the kubelet's own failure threshold, the probe hands a fast shutdown request to
the lifecycle loop and only then fails. The request is handed over
synchronously, within a bounded budget, so with the default probe settings the
outcome no longer depends on which of the two racing paths reaches the instance
manager first: previously the kubelet's SIGTERM and the shutdown request were
triggered by the same probe call, and if the signal won, the smart shutdown was
back. The budget leaves ample room at those settings; a
timeoutSecondscutwell below the default can still take it away. An instance stopped because it
was isolated is not restarted in place, so a container that comes back while
the partition is still there does not start PostgreSQL again.
Smart shutdown remains the right behaviour for every other path that reaches
this code, a rolling update, a pod deletion, a node drain, where not killing
user sessions is the point. No shutdown other than the isolation one changes.
The liveness probe also stops evaluating isolation for a fenced instance, which
has no PostgreSQL to stop and should not be restarted over connectivity it can
do nothing about.
Measured on a four-node kind cluster with a three-instance asynchronous cluster
and default probe settings, writing from a single session opened before the
partition. Before, the isolated primary acknowledged its last commit 204 seconds
after the node was disconnected; after, 26 seconds, which is the liveness
probe's own detection latency and not the shutdown. The documentation is
corrected as well: on a loaded primary the fast shutdown is expected to escalate
to an immediate one rather than complete, because the mandatory shutdown
checkpoint is unbounded, and that costs nothing beyond crash recovery on the
next start.
Closes #11280