Repository navigation
Retry the integration test webhook server when it loses its port - #9211
cert-manager-prow[bot] merged 3 commits into
Conversation
The test webhook server picks its port by binding to port 0, reading back the port it was allocated, closing that listener and then binding again to the same number. Anything on the machine can claim the port in the gap. `go test ./...` runs the integration test packages concurrently and each one starts its own webhook server, so they race each other for it. Losing that race was fatal rather than merely unlucky, because Server.Port reports the port number as soon as it has been chosen, which is before the listener has been created. StartWebhookServer polled Port, saw a number and handed the caller a URL for a server that had already exited. Every request to it was then refused, and the failure surfaced as a confusing assertion mismatch in an unrelated test rather than as the bind error. Wait for the port to accept a TLS connection before returning it, verifying the peer against the CA generated for the server so that another process holding the port cannot be mistaken for ours; watch the error channel while polling so a server that stops is reported immediately; and retry the whole startup on EADDRINUSE, which allocates a different port. The race cannot be closed in freePort itself: that needs controller-runtime to accept a pre-bound listener, and webhook.Options has no such field. Signed-off-by: Richard Wall <[email protected]>
wallrj-cyberark
left a comment
There was a problem hiding this comment.
Flagging the choices a reviewer is most likely to want justified.
| } else { | ||
| // The caller supplied its own TLS files, so there is no CA to check | ||
| // against and reaching the port has to be good enough. | ||
| tlsConfig.InsecureSkipVerify = true |
There was a problem hiding this comment.
InsecureSkipVerify here is deliberate but narrow, so worth calling out.
It is only reached when the caller passed --tls-cert-file/--tls-private-key-file themselves, in which case CAPEM is empty and there is no CA available to check against. The connection is thrown away immediately; it exists only to answer "is this port accepting connections yet".
In the normal path — the one every current caller takes — caPEM is set and the probe pins to it. That pinning is load-bearing rather than cosmetic: without it, a different webhook server that won the race for this port would satisfy the readiness check, and we would hand the caller its URL.
Happy to make the no-CA case fall back to a plain TCP dial instead if reviewers would rather not see the flag at all.
There was a problem hiding this comment.
load-bearing
Claude loves this expression.
[human]
| // then refused. The deadline covers the TLS handshake as well as the | ||
| // connection, so that a listener which never replies cannot wedge the | ||
| // poll; a loopback handshake takes single-digit milliseconds. | ||
| dialCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond) |
There was a problem hiding this comment.
The deadline covers the handshake, not just the connect, and that matters.
An earlier version of this used tls.Dial with no deadline. A listener that accepts the TCP connection but never speaks TLS — which is exactly what a squatting process looks like — leaves the handshake blocked forever, and the poll loop wedges until the whole test binary times out. Using DialContext with a deadline bounds both phases.
250ms is generous for loopback, where a handshake is single-digit milliseconds.
| conn, err := dialer.DialContext(dialCtx, "tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(port))) | ||
| cancel() | ||
| if err != nil { | ||
| return false, nil //nolint:nilerr // not listening yet, keep polling |
There was a problem hiding this comment.
Swallowing the dial error is intentional: at this point the server has chosen a port but may not have finished binding, so a refused connection is the expected state and we keep polling. A genuine startup failure is not lost — it arrives on errCh and is picked up by the select at the top of this poll function.
| } | ||
|
|
||
| // Port returns the port number that the webhook listener is listening on | ||
| // Port returns the port number the webhook listener has been assigned. It |
There was a problem hiding this comment.
This is a comment-only change, but it is the part I would most like a second opinion on.
The previous wording — "returns the port number that the webhook listener is listening on" — is not true, and believing it is what produced the bug this PR fixes. Callers reasonably read it as a readiness signal when it is only "a number has been picked".
There was a problem hiding this comment.
Pull request overview
This PR reduces flakiness in cert-manager’s integration tests by making the test webhook server startup robust against the known port selection race (port chosen via bind-to-:0 then re-bind), and by ensuring the helper only returns once the server is actually accepting TLS connections.
Changes:
- Add retry-on-
EADDRINUSEbehavior toStartWebhookServerand surface server startup failures promptly by monitoring theRunerror channel while polling. - Replace “port chosen” readiness with a real “TLS connection succeeds” readiness probe (verifying against the generated CA when available).
- Add a deterministic unit test that reproduces the port-race condition and asserts the helper retries and returns a reachable server; update misleading comments on
freePort/Port.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| test/webhook/testwebhook.go | Adds retry logic and a TLS-based readiness check that waits for the listener to truly accept connections (and fails fast if the server exits). |
| test/webhook/testwebhook_test.go | New unit test that deterministically squats on a port to validate retry behavior and confirm the returned server is reachable over TLS with the expected CA. |
| pkg/webhook/server/server.go | Clarifies freePort/Port doc comments to reflect the real behavior (port chosen vs actually listening). |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
Tolerate probe connection close errors, document the unverified caller-supplied-TLS path, and fix a spelling nit. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Richard Wall <[email protected]>
Bound waitForListener at 30 seconds so a server that can never pass the probe fails fast instead of hanging until the go test deadline. Publish the chosen webhook port through an atomic instead of writing ListenAddr from the Run goroutine, closing a data race with Port that go test -race flags. Correct the freePort comment: --secure-port=0 passes validation for any deployment, not just tests. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: Richard Wall <[email protected]>
|
/test pull-cert-manager-master-make-test |
|
I've given a look with my human eyes, and it looks OK to me. /lgtm |
|
[APPROVALNOTIFIER] This PR is APPROVED This pull-request has been approved by: maelvls The full list of commands accepted by this bot can be found here. The pull request process is described here DetailsNeeds approval from an approver in each of these files:
Approvers can indicate their approval by writing |
Pull Request Motivation
The integration tests are flaky, and when they fail they blame the wrong thing.
The test webhook server picks its port by binding to port 0, reading back the port it was allocated, closing that listener and then binding again to the same number —
freePortinpkg/webhook/server/server.go. Anything on the machine can claim the port in the gap.go test ./...runs the integration test packages concurrently and each one starts its own webhook server, so they race each other for it.Losing that race was fatal rather than merely unlucky.
Server.Portreports the port number as soon as it has been chosen, which is before the listener has been created.StartWebhookServerpolledPort, saw a number, and handed the caller a URL for a server that had already exited. Every request to it was then refused, so the failure surfaced in some unrelated test as a confusing assertion mismatch:The real cause is on the last line, and it is easy to miss underneath a failing assertion about key usages.
What this changes
Three things in
test/webhook, plus two comment corrections:Port(). The probe verifies the peer against the CA generated for the server, so another process holding the port cannot be mistaken for ours. This is whatDefaultServer.StartedCheckerdoes; it is not reachable here becauseServer.Rundoes not keep the manager it builds.EADDRINUSE(5 attempts). A fresh attempt is allocated a different port.The error from
Runis now wrapped with%wsoerrors.Is(err, syscall.EADDRINUSE)works. The poll interval drops from 100ms to 10ms, which is where most of the speed-up below comes from. The redundantos.RemoveAll(tempDir)goes, sincet.TempDir()already cleans up.The doc comment on
Portsaid it "returns the port number that the webhook listener is listening on", which is not true and is the trap that made this easy to write. It andfreePortnow say what they actually do. No behaviour changes outside tests —freePortis only reachable with--secure-port=0.Why not fix the race itself?
Binding port 0 and asking the server which port it got would remove the race rather than tolerate it, but controller-runtime permits neither half of it.
webhook.Options.Port = 0does not mean "any port" —setDefaultsrewrites it toDefaultPort. AndDefaultServer.Startcreates its listener as a local variable and never exposes it: noAddr(), noPort(), and noListenerfield onOptionsto pass a pre-bound listener in. Implementing thewebhook.Serverinterface ourselves would mean duplicatingStart, which importspkg/internal/httpserverandpkg/webhook/internal/metrics; dropping the latter would silently remove thecontroller_runtime_webhook_*metrics from the shipped webhook.SO_REUSEADDRdoes not help either. Go already sets it on every listener, and for TCP it only waivesTIME_WAITconflicts — it has never permitted two live listeners on one port.SO_REUSEPORTdoes, and would be worse: both servers would bind and the kernel would split connections between them.For contrast, the healthz listener a few lines further down in the same file does it correctly —
lc.Listen(ctx, "tcp", ":0"), keeping the listener it was given. Only the webhook port has this problem.Testing
TestStartWebhookServerRetriesWhenItsPortIsTakenreproduces the failure deterministically: it holds a port open, forces the first attempt onto it, and asserts that the helper retries and returns a server that is genuinely reachable over TLS with the expected CA. It needs no apiserver, so it runs in the normal unit test job.To confirm the test actually catches the bug rather than passing vacuously, I set
startAttempts = 1and re-ran it:With the retry restored it passes, and the log shows both attempts:
The full integration suite passes:
golangci-lint runover the whole repo reports 0 issues.I could not find an existing issue for this, so there is nothing to link.
Kind
/kind flake
Release Note