Repository navigation
fix(tcp): connect-timeout accounting, expect-proxy timer, SNI preread, PROXY half-close and relay source fixes - #1934
Merged
Merged
Conversation
A TCP backend connection still not established when `connect_timeout` expires closed the session, as the documented TCP exception requires (a TCP session is not failed over), but the timeout never reached the accounting a refused connection goes through. The backend timer is armed for `connect_timeout` in `connect_to_backend` and only switches to `back_timeout` in `set_back_connected`, and the backend arm of `TcpSession::timeout` only called `container_backend_timeout.triggered()`. `Server::timeout` runs no `ready` pass for TCP (`ProxySession::needs_ready_pass` is `false`), and `TcpSession::fail_backend_connection`, the only place that bumps `Backend::failures`, arms the retry policy and emits `backend.connections.error`, `backend.down` and `backend.available`, was called only from the HUP branch of `ready_inner`. A blackholed TCP backend (SYN dropped, accept queue full) therefore never entered its back-off window, the load balancer kept selecting it, and every client routed to it waited the full `connect_timeout` before being closed. The backend arm of `TcpSession::timeout` now calls `fail_backend_connection` when the dial is still `Connecting`, then still closes the session. A timer firing on a `Connected` backend is an idle `back_timeout` and charges nothing. Nothing is released twice: `fail_backend_connection` touches only the failure count, the retry policy and the error and down metrics, and the connection release in `TcpSession::close` runs once as before. `CHANGELOG.md`, the `connect_timeout` row and the TCP failover paragraph of `doc/configure.md`, `doc/lifetime_of_a_session.md` and the `max_connection_attempts` comment of `bin/config.toml` describe the new accounting. Tests: - `tcp::sni_routing_tests::a_backend_connect_timeout_is_charged_to_the_backend` fires the backend timer of a still-`Connecting` dial and asserts the session closes with `failures == 1` and one retry-policy try (unfixed: `left: 0 right: 1`). - `tcp::sni_routing_tests::a_backend_idle_timeout_is_not_charged_to_the_backend` is its pair: the same timer on a `Connected` backend closes the session and charges nothing. Signed-off-by: Florentin Dubois <[email protected]>
… connect Once a ClientHello routes a TCP SNI-preread session, the route latches in `SniPreread::outcome`, and frontend HUP interest stays armed while the backend dial is still `Connecting`. A client FIN or RST then reached `TcpSession::front_hup`, `SniPreread::on_front_closed` and `front_gone`. The accumulator still held the ClientHello, so `Input::FrontClosed` went into the already-decided core, which replayed the latched `Output::Routed` through `handle_output` a second time: release builds counted `tcp.sni_preread.routed` twice and logged the route twice, and debug builds aborted the worker on `debug_assert!(self.outcome.is_none(), ...)`. `SniPreread::front_gone` now returns `SessionResult::Close`, with a `debug!` line, before it looks at the accumulator whenever a route has already latched, as the route-aware front timeout in `TcpSession::timeout` already does (#1290). The guard sits in the shared helper, so the read-error path is covered as well as the HUP path. The session still closes through the existing teardown, exactly once. The doc comment of `SniPreread::on_front_closed` no longer claims it only runs before a routing decision. `CHANGELOG.md` and the tcp_preread `LIFECYCLE.md` describe the new behaviour. Test: - `tcp::sni_routing_tests::frontend_hup_after_route_with_pending_dial_does_not_replay_the_route` routes a session, leaves its dial `Connecting`, delivers a frontend HUP and runs one `ready()` pass: the pass must not panic, must still close the session, and `routed` must move by exactly one. Unfixed, it panics with "a route must be captured at most once per SniPreread lifetime", and with debug assertions off it fails with `left: 2 right: 1`. Signed-off-by: Florentin Dubois <[email protected]>
…d timer On an `expect_proxy` TCP listener, `TcpSession::new` gave `ExpectProxyProtocol` a clone of the session's frontend `TimeoutContainer`, and `ExpectProxyProtocol::into_pipe` passed that clone on to the `Pipe`. A clone shares the timer wheel handle but not the entry it names, so a reset only the session performed (`TcpSession::set_back_connected`, or `TcpSession::readable` ahead of the pipe's own reset) left the pipe with a stale handle, and the pipe re-armed a second entry under the same token. When that second entry fired first, `TcpSession::timeout` discarded the session's own live entry with `triggered()`. Nothing could cancel that entry any more: it later fired under a slab key reused by an unrelated TCP session, which was closed with no deadline check. It takes two frontend reads while the backend connect is pending, a connect that completes on a later wheel tick, both peers going quiet, and a `front_timeout` exceeding `back_timeout` by less than the time the connect took; the 60 s and 30 s defaults are never affected. `TcpSession::new` now hands `ExpectProxyProtocol` an empty container (`TimeoutContainer::new_empty`), and `ExpectProxyProtocol::into_pipe` builds the `Pipe` with no frontend timer, so the session keeps the only frontend deadline, as the plain, send-proxy, relay and SNI-preread pipes already do. The session resets that entry wherever the pipe reset its clone, so no session closes earlier than before, and the `Could not reset front timeout (pipe)` error log disappears on this path. HTTP and HTTPS never call `into_pipe` and are unchanged. `CHANGELOG.md`, `doc/lifetime_of_a_session.md` and the proxy_protocol `LIFECYCLE.md` describe the new wiring. Test: - `tcp::sni_routing_tests::expect_proxy_pipe_leaves_no_orphan_frontend_timer_after_a_timeout` drives an expect-proxy session through the stale-clone sequence and asserts that no orphan frontend entry fires after the timeout, that the expect stage holds no armed entry, and that the pipe carries no frontend timer. Unfixed, it fails with `entries fired at +[30, 34]s`; each half of the fix alone fails one of the two structural assertions. Signed-off-by: Florentin Dubois <[email protected]>
On an SNI-routed TCP listener a client can send its ClientHello and half-close right behind it, and Linux then reports both as one `READABLE | HUP` event. `TcpSession::ready_inner` honoured the HUP before reading. `SniPreread::front_gone` looks at the accumulator, not at the kernel queue, so a session whose hello was still unread was closed as a silent bare-TCP health check: `trace!` only, no `tcp.sni_preread.routed` or `tcp.sni_preread.rejected.*` count. A hello whose last fragment arrived together with the FIN was counted as `rejected.front_closed`, although the rest of it was already queued. The pre-HUP drain in `TcpSession::ready_inner`, which ran only for `ExpectProxyProtocol` (#1823), now also runs for an `SniPreread` that has not routed yet, so the pending bytes reach the core before the HUP is acted on. A complete hello is routed and counted once, then the still-set HUP closes the session through the route-latched arm of `SniPreread::front_gone` without dialing the backend; a malformed one is rejected with the reason it earns; a hello the FIN cut short is metered `rejected.front_closed`; and a connect that sent nothing stays silent. Teardown reuses the existing `front_hup` path and releases nothing new. The comments of `SniPreread::front_gone` and `on_front_closed` and the tcp_preread `LIFECYCLE.md` §9 now describe a route latched in that drain as well as during a pending dial. `CHANGELOG.md`, `doc/lifetime_of_a_session.md` and the tcp_preread `LIFECYCLE.md` describe the new behaviour. Tests: - `tcp::sni_routing_tests::sni_preread_hello_and_fin_in_one_event_is_routed_not_a_silent_health_check` delivers a complete hello and a FIN in one real epoll event. - `tcp::sni_routing_tests::sni_preread_last_fragment_and_fin_in_one_event_is_routed_not_rejected` reads the first half of the hello in an earlier pass, then delivers the second half and the FIN in one event. Both fail on the unfixed tree at their final routed-count assertion (`left: 0 right: 1`). Signed-off-by: Florentin Dubois <[email protected]>
… PROXY clusters
On a TCP cluster that sends a PROXY header to its backend
(`send_proxy = true`), a relay cluster when the listener has
`expect_proxy = true` and a send cluster otherwise, a client may write
its request and FIN before the worker services the socket. The first
`TcpSession::ready_inner` pass only dials, so the coalesced
`READABLE | HUP` was still pending on the next pass, which handed it to
the wildcard arm of `TcpSession::front_hup`. That closed the session
before `RelayProxyProtocol::back_writable` or
`SendProxyProtocol::back_writable` had written anything: the backend saw
a connection dialed and then closed with nothing written, without even
its PROXY header on a send cluster, and the client's own header and
request were dropped on a relay one. An `expect_proxy` listener without
`send_proxy` was not affected: it already reads the queued bytes before
acting on the HUP.
`TcpSession::ready_inner` now drains a relay session's readable bytes
before its HUP check, and a new `TcpSession::defers_frontend_hup` keeps
the HUP of a send session, and of a relay session once its header is
parsed, in the readiness event while masking it out of the dispatch
loop's frontend interest. The HUP then reaches the existing teardown,
`Pipe::frontend_hup`, through the existing upgrade: the header and the
request are forwarded, and the pipe closes the session once nothing is
left in flight. A relay client that half-closes inside its PROXY header
still closes at once, ERROR still closes at once, and no new release
path is added. A send session reads nothing before the upgrade, so a
bare connect and FIN, typically an L4 health check, now waits for the
backend connect and costs the backend one connection that carries only
the PROXY header; the wait is bounded by the connect, `connect_timeout`
and the frontend timeout.
`CHANGELOG.md`, `doc/lifetime_of_a_session.md` and the proxy_protocol
`LIFECYCLE.md` describe the new behaviour.
Tests (in `tcp::sni_routing_tests`):
- `relay_proxy_protocol_half_close_before_backend_connect_forwards_the_request`
- `send_proxy_protocol_half_close_before_backend_connect_forwards_the_request`
Both fail on the unfixed tree on the delivery assertion ("the backend
must receive it, got []"). Guards for each arm of the new predicates:
- `relay_proxy_protocol_front_hup_while_connecting_waits_for_the_backend`
- `send_proxy_protocol_front_hup_while_connecting_waits_for_the_backend`
- `relay_proxy_protocol_half_close_without_any_byte_closes_at_once`
- `relay_proxy_protocol_half_close_inside_the_header_closes_at_once`
- `send_proxy_protocol_bare_half_close_delivers_only_the_header_then_closes`
- `send_proxy_protocol_reset_while_connecting_closes_at_once`
Signed-off-by: Florentin Dubois <[email protected]>
The recipe of tcp::sni_routing_tests::a_backend_connect_timeout_is_charged_to_the_backend said "run it unmodified" and named no statement to mutate. It now names the statement and the failure it produces: delete the `self.fail_backend_connection();` call from the `is_connecting()` block in the backend arm of `TcpSession::timeout`, and the `failures` assertion fails with "a connect timed out on connect_timeout must be counted against its backend". The mutation was applied and the test seen failing on its own assertion, then the code was restored. Comments only. Signed-off-by: Florentin Dubois <[email protected]>
…is parsed A `RelayHeader` TCP session (a cluster with `send_proxy = true` behind a listener with `expect_proxy = true`) dialed its backend on its first readiness event, before `RelayProxyProtocol::readable` had parsed the inbound PROXY-v2 header. `TcpSession::attempt_backend_connect_if_needed` excluded only `ExpectProxyProtocol` and an unrouted `SniPreread`. With nothing parsed, `TcpSession::effective_session_address` fell back to the accepted peer, which is the upstream load balancer, so the per-(cluster, source-IP) and per-subnet slots (`max_connections_per_ip`, `max_connections_per_subnet`) were charged to the load balancer for every client behind it, and the affinity key of `HRW`, `MAGLEV` and `shard_percent` was derived from it too. `attempt_backend_connect_if_needed` now returns early for a `RelayProxyProtocol` whose `header_size` is still `None`, so a relay session dials through the attempt that follows the `readable()` call that parses its header, and is charged to the header's source address. The pre-HUP drain in `TcpSession::ready_inner` also gets one dial attempt, restricted to a relay session, so a header coalesced with the client's FIN does not leave the session undialed until the frontend timeout. The dial and the release are the existing `connect_to_backend` and close paths. A `LOCAL` / `AF_UNSPEC` header still falls back to the peer, as documented. A relay session no longer overlaps its backend connect with the wait for the header, and a relay connection that never completes a header (a bare health check, a slow or garbage client) opens no backend connection at all. The comments of `ready_inner` and of the half-close test helper now describe the parse-then-dial order, and the relay front-HUP test sends only its payload, since its fixture now writes and parses the header before dialing. `CHANGELOG.md`, `doc/lifetime_of_a_session.md`, `doc/rate-limit-design.md` and the proxy_protocol `LIFECYCLE.md` describe the new behaviour. Test: - `tcp::sni_routing_tests::a_relay_proxy_protocol_session_is_charged_to_the_header_source_not_the_lb_peer` connects from 127.0.0.1 (the load balancer) and relays a header whose source is 192.0.2.7, and asserts that no slot is held before the header, that the slot is charged to 192.0.2.7 after it, and that 127.0.0.1 holds none. On the unfixed tree it fails with "the per-IP slot must not be charged to the load balancer's peer address before its PROXY header is read". Signed-off-by: Florentin Dubois <[email protected]>
Signed-off-by: Florentin Dubois <[email protected]>
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.
Six defects in the TCP proxy session, one commit each, plus one commit that repairs a test's red recipe. The listener-removal socket leak is fixed separately in #1931.
A backend connect that timed out was never charged to its backend (accounting drift). The backend arm of
TcpSession::timeoutclosed the session onconnect_timeoutbut never reachedTcpSession::fail_backend_connection, the only place that bumpsBackend::failures, arms the retry policy and emitsbackend.connections.errorandbackend.down. A blackholed TCP backend never entered its back-off window, so every client routed to it waited the fullconnect_timeout. The timeout of a still-Connectingdial is now charged like a refused connection; a timer firing on an established backend is still an idle timeout and charges nothing.A hang-up during the backend connect replayed the SNI route (race replay). After a ClientHello routed a session, a frontend HUP while the dial was still
ConnectingfedInput::FrontClosedinto the already-decided preread core, which replayedOutput::Routed:tcp.sni_preread.routedcounted twice in release builds and a debug build aborted the worker on adebug_assert!.SniPreread::front_gonenow closes the session without routing it a second time once a route has latched.An expect-proxy pipe kept a clone of the session's frontend timer (resource leak, timer leak). The clone shared the wheel handle but not its entry, so the pipe could arm a second entry under the session token; when it fired first, the session's own entry could no longer be cancelled and later closed an unrelated TCP session that reused the slab key. The session now owns the only frontend timer and the pipe is built without one, as on every other TCP path.
A ClientHello and FIN in one event were metered as a silent health check (misleading signal).
TcpSession::ready_innerhonoured the HUP before reading, so a session whose hello was still queued in the kernel was closed with noroutedorrejected.*count, and a last fragment arriving with the FIN was counted asrejected.front_closed. The pre-HUP drain that already ran forexpect_proxynow also runs for an undecided SNI preread.A request half-closed before the backend connect was dropped on PROXY clusters (teardown loss). On a relay or send (
send_proxy = true) cluster, a client's request and FIN reported in one event closed the session in the PROXY state before anything was written to the backend. A relay session's pending header is now read first, and the HUP of a send session, or of a relay session with a parsed header, waits for the upgrade so thePipeforwards the request and then closes.A relay session was charged to the load balancer instead of the client its PROXY header names (accounting drift). A relay session dialed its backend on its first readiness event, before its inbound PROXY header was parsed, so
TcpSession::effective_session_addressfell back to the accepted peer: the per-IP and per-subnet slots, and theHRW,MAGLEVandshard_percentaffinity keys, were derived from the upstream load balancer for every client behind it. A relay session now dials only once its header is parsed, through the attempt that follows the read that parses it, and the pre-HUP drain gives a header coalesced with the client's FIN its one dial attempt.The
TO SEE THIS REDrecipe ofa_backend_connect_timeout_is_charged_to_the_backendnow names the statement to delete and the failure it produces, which was executed (comments only).Each fix is recorded in
CHANGELOG.md(Unreleased, Fixed);doc/configure.md,doc/lifetime_of_a_session.md,doc/rate-limit-design.md,bin/config.tomland the tcp_preread and proxy_protocolLIFECYCLE.mdfiles follow the changes.Behaviour changes
backend.connections.errorand can mark a backend down (backend.down, aBackendDownevent), with its back-off window.routedorrejected.front_closedinstead of closing silently; the session still closes and no backend is dialed.send_proxycluster, a bare connect and FIN (typically an L4 health check) now waits for the backend connect and sends that backend a PROXY header before closing, instead of closing a dialed connection with nothing written. The wait is bounded byconnect_timeoutand the frontend timeout.send_proxy = truebehind anexpect_proxylistener), clients behind one load balancer are now counted and pinned per client, by their PROXY header's source address. The backend connect no longer overlaps the wait for the header, which can add up to one connect time to the start of each relayed session, and a relay connection that never completes a header (a bare health check, a slow or garbage client) no longer opens a backend connection. ALOCAL/AF_UNSPECheader still falls back to the peer.Tests added
tcp::sni_routing_tests:a_backend_connect_timeout_is_charged_to_the_backenda_backend_idle_timeout_is_not_charged_to_the_backendfrontend_hup_after_route_with_pending_dial_does_not_replay_the_routeexpect_proxy_pipe_leaves_no_orphan_frontend_timer_after_a_timeoutsni_preread_hello_and_fin_in_one_event_is_routed_not_a_silent_health_checksni_preread_last_fragment_and_fin_in_one_event_is_routed_not_rejectedrelay_proxy_protocol_half_close_before_backend_connect_forwards_the_requestsend_proxy_protocol_half_close_before_backend_connect_forwards_the_requestrelay_proxy_protocol_front_hup_while_connecting_waits_for_the_backendsend_proxy_protocol_front_hup_while_connecting_waits_for_the_backendrelay_proxy_protocol_half_close_without_any_byte_closes_at_oncerelay_proxy_protocol_half_close_inside_the_header_closes_at_oncesend_proxy_protocol_bare_half_close_delivers_only_the_header_then_closessend_proxy_protocol_reset_while_connecting_closes_at_oncea_relay_proxy_protocol_session_is_charged_to_the_header_source_not_the_lb_peerEach proving test fails without its fix and passes with it; the pair and guard tests pin the cases a fix must leave alone.
Validation
Run locally on the final tree with the pinned toolchain (Rust 1.93.1, rustfmt from nightly), with
CARGO_PROFILE_DEV_DEBUG=0:cargo +nightly fmt --all -- --check: exit 0, no output.cargo clippy --all-targets --locked -- -D warnings: exit 0,Finished dev profile, no warning.cargo clippy --all-targets --release --locked --features opentelemetry,splice,simd -- -D warnings: exit 0,Finished release profile, no warning.RUSTDOCFLAGS='-D warnings' cargo doc --no-deps --all-features --locked: exit 0.cargo test --workspace --locked --no-fail-fast -- --skip tests::fuzz_tests::: exit 0.sozu-lib1745 passed; 0 failed,sozu-e2e693 passed; 0 failed,sozu-command-lib416 passed; 0 failed,sozulib and bin273 passed; 0 failedeach, every other integration and doc-test target ok.cargo test -p sozu-lib --locked --features opentelemetry,splice,simd:1772 passed; 0 failed, every integration and doc-test target ok.cargo test -p sozu --locked --test <suite> -- --ignored: all ok.cargo test -p sozu-e2e --locked --features grpc-e2e tests::grpc_tests:::2 passed; 0 failed.RUSTFLAGS='--cfg tokio_unstable' cargo test -p sozu-sim --locked --test tcp_preread_sim -- --nocapturewith the CI step'sSOZU_TCP_PREREAD_SIM_SEEDS=512andSOZU_TCP_PREREAD_SIM_STEPS=64:6 passed; 0 failed.#[ignore]): ok.python3 .github/scripts/check_doc_citations.py --base c6098095d3a2c1738a90cfbc17865f718d648276, with the self-test and the broken-fixture check: exit 0, every ruleOK.TO SEE THIS REDrecipe was executed on the final tree: with theRelayProxyProtocol/header_size.is_none()early return ofTcpSession::attempt_backend_connect_if_neededdeleted, the test fails on "the per-IP slot must not be charged to the load balancer's peer address before its PROXY header is read"; the code was then restored.Not run
The other crypto-provider cells (
crypto-aws-lc-rs,crypto-openssl,fips) and the stable, beta and nightly cells; dev-profile clippy withopentelemetry,splice,simd; the cargo-fuzz targets; the benches; the/procobserver suites (they need a user namespace); the real-service protocol suites, including the TCP ones (they pull container images); the UDP, H2, backend selection and mutable-commands simulation sweeps. No test asserts the affinity-key half of the relay fix (HRW, MAGLEV, shard): it follows from the same dial-time address, by reading.Cargo.lockis unchanged, so the RUSTSEC advisory job sees the base lockfile.