Repository navigation
Add clickhouse-proxy application mode - #110105
alexey-milovidov wants to merge 169 commits into
Conversation
Implement a new `proxy` application mode in the `clickhouse` binary. The proxy accepts connections over end-user ClickHouse protocols, chooses a backend from a configurable routing table, and forwards the traffic to it. It runs on the `silk` fiber framework so a large number of connections can be handled with low memory usage. Features: - Frontends for HTTP(S), native TCP, MySQL, PostgreSQL, transparent TLS routing by SNI, and opaque TCP streams. The user name and the database are parsed from the first packets where the protocol allows it (HTTP headers/params, native `Hello`, PostgreSQL `StartupMessage`); query-type routing is supported for HTTP. - Multi-criteria routing rules matching on host (SNI or HTTP `Host`), user, database, query type and protocol, by exact value or regular expression; regexp captures can be substituted into a backend address template. - Pools of backends with pluggable load balancing (`random`, `round_robin`, `least_connections`, `lowest_latency`, `least_resources`) behind a common interface, and session stickiness by `session_id` or peer address using a consistent (rendezvous) hash. - TLS termination and re-encryption, TLS unwrapping, or transparent SNI-based forwarding, with optional ACME certificate provisioning. - Backend health monitoring (connect latency, consecutive failures) and optional CPU/memory polling via per-backend credentials, plus a JSON status endpoint, `/ping`, and static pages served by the proxy itself. - Abstract routing table with hooks (unknown route, no backends available, first time a user or a database is seen) that can run a shell command to, for example, provision a backend on demand. The server-side `Silk::SecureFiberStreamSocketImpl` gains a constructor that adopts an accepted fd and performs the server-side TLS handshake over the silk fiber BIO, so a TLS-terminating listener never blocks an OS thread. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
|
Workflow [PR], commit [a19dceb] Summary: ❌
AI ReviewSummaryAdds the standalone Missing context / blind spots
Findings❌ Blockers
Tests
Final VerdictStatus: ❌ Block Fix SSH byte preservation, accept-loop ownership, first-seen rollback/completion, and the complete cancellation deadline. Settle the three documented MySQL/health contract limitations above, and provide focused regression evidence for the corrected failure paths. |
SSH carries no cleartext identity (no SNI, and the user name is inside the encrypted transport), so the proxy now terminates SSH to route it. A new `ssh` listener protocol: - terminates SSH using the existing libssh server wrappers (`SSHBind`/`SSHSession`), presenting the proxy's own host key; - reads the client's offered public key in the `auth_pubkey` callback and routes by it — a new `authorized_key` / `authorized_key_file` routing dimension chooses the pool from the key the client presents (the user name is captured too); - re-originates a fresh SSH connection to the chosen backend as a bastion, authenticating with a configured `backend_key_file` that the backends trust, and splices the two sessions (pty, shell, exec, stdin/stdout/stderr, EOF, exit status). Because the client's signature is bound to the client-facing session it cannot be replayed to the backend; the proxy authorizes the client by its public key and logs in to the backend as a jump host. Each SSH connection runs under a silk `ThreadModeScope` (libssh drives its own blocking I/O), and routing inside the libssh callbacks uses a new pure `Router::routeStatic` that never touches fiber primitives. Validated end to end: a keyed `ssh` client through the proxy to a backend `sshd` runs a remote command and returns its output; an unknown key is rejected. Co-Authored-By: Claude Fable 5 <[email protected]>
- Use angle-bracket includes for the proxy's own headers, as the style check requires (the program directory is on the include path). - Add comments containing "Ok" to the six catch (...) blocks flagged by the catch_all style check, explaining why swallowing the exception is acceptable at each site. - Avoid "--" inside an XML comment in proxy_config.xml (use the short option -C in the usage example), fixing the xmllint check. - Fix clang-tidy errors from the arm_tidy build: initialize int n in FiberSocket::sendAll, add default member initializers to the TLS ClientHello Cursor and to AcceptState::params, replace an ambiguous supervisor_future.reset() with an assignment of nullptr, and bind the HTTP path to a const reference instead of copying it. Style check report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=7e580b6789e744485cb5dbfb57dfd479bfcc503a&name_0=PR&name_1=Style%20check Build (arm_tidy) report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=7e580b6789e744485cb5dbfb57dfd479bfcc503a&name_0=PR&name_1=Build%20%28arm_tidy%29 PR: #110105 Co-Authored-By: Claude Fable 5 <[email protected]>
The test_numbers_check style check does not allow gaps larger than 100 between consecutive stateless test numbers, and the largest number on master is currently 04511. Style check report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=7e580b6789e744485cb5dbfb57dfd479bfcc503a&name_0=PR&name_1=Style%20check PR: #110105 Co-Authored-By: Claude Fable 5 <[email protected]>
…lication The fast test builds with USE_SILK = 0, where ProxyServer.h defines nothing and Proxy::ProxyServer stays an incomplete type. The implicit destructor of ProxyApplication, instantiated in Proxy.cpp, then cannot destroy the std::unique_ptr member. Compile the member only when silk is available; all its uses were already guarded. Fast test report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=7e580b6789e744485cb5dbfb57dfd479bfcc503a&name_0=PR&name_1=Fast%20test PR: #110105 Co-Authored-By: Claude Fable 5 <[email protected]>
MySQL is server-speaks-first, so when a routing rule needs the user or the database the proxy now terminates the handshake instead of forwarding blindly: it greets the client, reads the `HandshakeResponse` (user, database), and routes on them. Because the client's authentication response is bound to the scramble in the greeting, the proxy connects to the chosen backend, reads the backend's scramble, and issues an auth-switch so the client re-computes its response against the backend's scramble, which the proxy forwards verbatim. The backend performs the real password check; the proxy never learns the password. After authentication the connection is spliced byte for byte. When no rule needs the user or the database, MySQL is forwarded transparently as before. Reuses the existing MySQL packet classes (`Handshake`, `HandshakeResponse`, `AuthSwitchRequest`, `AuthSwitchResponse`, `ERRPacket`) over `ReadBufferFromPocoSocket`/`AutoCanceledWriteBuffer` on the fiber socket, so it stays cooperative (no OS-thread blocking). Validated end to end with both the mariadb CLI and pymysql: routing by database and by user return the backend's query results through the proxy; an unroutable database is rejected with a MySQL error. Co-Authored-By: Claude Fable 5 <[email protected]>
Align MySQLFrontend.cpp with the include style used across the proxy sources. Co-Authored-By: Claude Fable 5 <[email protected]>
Without disabling Nagle's algorithm, relaying small protocol packets (e.g. a native `SELECT 1` request and its response) stalls on the Nagle/delayed-ACK interaction: a benchmark measured about 40 ms per round-trip through the proxy (~24 QPS) versus sub-millisecond direct. ClickHouse's own servers set TCP_NODELAY for the same reason. Set TCP_NODELAY on every proxy socket — accepted client connections and outgoing backend connections, plain and TLS — and on the SSH client fd. After the fix the same benchmark relays at roughly the same rate as a direct connection. Co-Authored-By: Claude Fable 5 <[email protected]>
A performance test showed bulk relaying is buffer-bound: with the previous 16 KiB per-direction buffer a single HTTP result stream reached only ~0.8 GB/s versus ~4 GB/s direct. Raising the buffer to 64 KiB reaches ~2 GB/s, and 256 KiB approaches the direct rate; the cost is roughly twice the buffer size in resident memory per actively-transferring connection. Make 64 KiB the default (a better throughput/memory balance) and document `relay_buffer_size` and `fiber_stack_size` as the two knobs that trade throughput against per-connection memory. Co-Authored-By: Claude Fable 5 <[email protected]>
Bump the silk submodule to pick up FiberScheduler::splice and use it to relay connections whose both legs are plaintext (HTTP, native, MySQL, PostgreSQL, transparent TLS-by-SNI, opaque streams): data is moved socket -> pipe -> socket entirely in the kernel instead of being copied through a user-space buffer. A TLS-terminated leg still uses the copy relay, since its bytes must be decrypted/encrypted in user space. A benchmark relaying a large HTTP result went from ~0.8 GB/s (copy, 16 KiB buffer) to line rate (~5 GB/s, matching a direct connection) with splice and a larger buffer, while small-query latency is unchanged (SPLICE_F_MOVE only, so the socket is not corked). Byte-for-byte identical output was verified against a direct connection. Co-Authored-By: Claude Fable 5 <[email protected]>
With the splice relay a 256 KiB chunk reaches near line rate, so make it the default (was 64 KiB). Update the tuning documentation accordingly. Co-Authored-By: Claude Fable 5 <[email protected]>
- Remove the unused error code `ALL_CONNECTION_TRIES_FAILED` from `Frontend.cpp`. - Replace `std::istringstream`/`std::ostringstream` with manual token parsing, `fmt::format`, and `ReadBufferFromFile` + `readStringUntilEOF`; the remaining `std::ostringstream` in `StatusPage.cpp` feeds `Poco::JSON` `stringify` (which requires `std::ostream`) and is allowlisted, as in `KeeperDashboardRequestHandler.cpp`. - Check the return value of `close` in cleanup paths via `[[maybe_unused]] int err`. Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=cff9eb708df3eedf58a2fe0dae28a8cb287da1b5&name_0=PR&name_1=Style%20check PR: #110105 Co-Authored-By: Claude Fable 5 <[email protected]>
The `arm_tidy` build failed with: programs/proxy/Relay.cpp:122:21: error: Value stored to 'remaining' is never read [clang-analyzer-deadcode.DeadStores,-warnings-as-errors] The `remaining = 0;` assignment sat right before a `break` that leaves the `while (remaining > 0)` inner loop, and `remaining` is not read after the loop, so the store was dead. Drop it; the `in_bytes = 0;` signal and the `break` already stop both loops. CI: https://s3.amazonaws.com/clickhouse-test-reports/PRs/110105/83f68d302c5aa8f84077edcc0f12e807848f31d6/build_arm_tidy/build_clickhouse/build_clickhouse.log Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nitizer `04512_proxy_http_routing` failed under MemorySanitizer with a `use-of-uninitialized-value` in `RecordingReader::readLine`, tracing back to the receive buffer filled by `Silk::FiberStreamSocketImpl::receiveBytes`. The bytes arrive through an `io_uring` completion, which MemorySanitizer does not intercept the way it does the plain `read`/`recv` syscalls, so it keeps treating them as uninitialized as soon as the proxy inspects the parsed request line. Unpoison the received region explicitly, mirroring what the TLS path in `SilkSecureFiberStreamSocketImpl` (`silkBioRead`) already does. The `__msan_unpoison` macro is a no-op outside MemorySanitizer builds, so this has no effect on release builds. CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=110105&sha=dca035adbcd7494dd7e399f210a72fedbf5c74a3&name_0=PR&name_1=Stateless%20tests%20%28amd_msan%2C%20flaky%20check%29 PR: #110105 Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The `HealthMonitor` polled every backend's resource usage on each liveness pass, so with the default `interval_ms` of `5000` and `resource_poll_interval_ms` of `10000` it polled resources twice as often as configured. The `last_resource_poll` member and the `resource_poll_interval_ms` setting were both present but never consulted. The supervisor fiber now decides per backend whether a resource poll is due (comparing `last_resource_poll` against `resource_poll_interval_ms`) before dispatching the check, and passes the decision to `checkBackend`. The throttle bookkeeping stays confined to the single supervisor fiber, as the `last_resource_poll` comment already promised. Addresses review feedback from `clickhouse-gh` on `programs/proxy/HealthMonitor.cpp`. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
|
Acknowledged. I'm investigating First finding: the test does not exercise the functions at all. All four |
|
The fix is in #131157. The four |
|
Acknowledged. I'm investigating why |
|
I looked at why
The query does almost no work per row ( I could not pin down which hardware structure is responsible (instruction TLB, branch predictor or cache sets). The measured runs collect no hardware counters, and in this job's profile runs |
Resolve the conflict in `src/Common/Silk/SecureFiberStreamSocketImpl.cpp`, which master moved from `src/IO` and where master now passes the underlying socket as a `Poco::AutoPtr` (fixing the same reference leak this PR fixed with `release`): keep master's constructor and build the server-side `accepted_fd` constructor of the proxy the same way. Update the includes in `programs/proxy/SocketIO.cpp` to the new paths.
…th requests by the generated query Address review on `programs/proxy/Frontend.cpp` and `programs/proxy/HTTPFrontend.cpp` in #110105 A `WITH` clause may contain `select` and `insert` as names, also as bare references in its expressions (`WITH 1 AS `select`, 1 + select + 1 AS x INSERT ...`), which a keyword scan cannot tell from the statement. A `WITH` query is now parsed with `ParserQuery`: it is an `insert` or a `select` as the server parses it, and has no query type if it does not parse, or if only a prefix of it was read (unless the prefix already reaches the inline data of an `INSERT`). For a URL path with a table (`/db/table.CSV`), the server generates the query itself: a `PUT` without a `query` parameter is an upload (`INSERT INTO table FORMAT format`, the body is data), and a request without a query and a body is `SELECT * FROM table`. The proxy now derives the query type from them instead of classifying the body of an upload as a query. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ts after EOF Address review on `programs/proxy/SSHFrontend.cpp` in #110105 The data callbacks leave what exceeds the bounded pending output in the libssh channel buffer. When the backend sends EOF, exit status and close, and then disconnects, its session enters the error state, in which `ssh_channel_read_nonblocking` fails before copying the buffered data, so the rest of the output was lost. Now the EOF callback moves the data still buffered by the source channel into the pending output. No data follows EOF, so this is bounded by the receive window. libssh sets the EOF of the channel before the callback, so these reads take only the buffered data and do not process further packets. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review on `programs/proxy/SSHFrontend.cpp` in #110105 The test starts an `ssh` listener in front of the server's SSH port and checks with the OpenSSH client that an allowlisted signed key gets through, that a probe of an allowlisted key without a signature, and a signed key that is not allowlisted (with a listener default pool and with a rule on the user name only) are denied without routing, and that a backend whose host key is not in `known_hosts_file` is refused. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master, which brings the fix for the |
`05768_proxy_ssh_authorization` printed the result of the allowlisted query and then `denied`: `ssh` exited with 255 although the backend returned exit status 0. After the splice the proxy closed the client channel and called `ssh_disconnect` at once, so `SSH_MSG_DISCONNECT` followed the exit status and the channel close immediately. When both arrive in one read, OpenSSH dispatches the disconnect before it acts on the closed channel and exits with 255 instead of the exit status. This happens under load, as in the ASan job. Wait, bounded by 5 seconds, for the client to close its side before disconnecting, as the SSH handler of the server does. Also remove the backend session from the event before freeing it. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110105&sha=cee0ab969d4eeda8a328e3904f2c35705e81d0e5&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20db%20disk%2C%20distributed%20plan%2C%20targeted%29 #110105 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🕵 Merged master and fixed the |
| size_t delivered = 0; | ||
| for (const auto & backend : ctx.router.reachableBackends(ctx.listener)) | ||
| { | ||
| /// A secure backend cannot be reached over this protocol (see `connectToBackend`). A backend that | ||
| /// is marked down still receives the request: `alive` only gates new routing, and the sessions that | ||
| /// were relayed to it before it was marked down may still be running there. | ||
| if (backend->config().secure) | ||
| continue; | ||
| try | ||
| { | ||
| const UInt16 port = backendPortFor(ListenerProtocol::PostgreSQL, backend->config(), ctx.listener.port); |
There was a problem hiding this comment.
[Blocker] Bound and cancel the complete PostgreSQL cancellation broadcast
This unauthenticated request serially connects to every reachable backend, including all dynamic backends and those marked down, with a fresh connect_timeout_ms for each. There is no deadline for the broadcast or shutdown check. With the default 10,000 dynamic-backend limit and 3-second connect timeout, unreachable endpoints can keep one handler running for about 30,000 seconds; cancellation of an otherwise healthy session is also delayed by whichever unavailable backends precede it.
The client handshake watchdog and ConnectionRegistry::shutdownAll only shut down the client socket. This loop no longer reads that socket, and it is not registered with abortAllRelays, so ProxyServer::stop waits in connections.waitAll until the entire fanout completes even after the client disconnects.
Give the whole broadcast a bounded budget and make shutdown interrupt its backend work. Please cover cancellation and shutdown with multiple unreachable backends.
There was a problem hiding this comment.
🕵 Fixed in 9cb9ef4. The backends now receive the request concurrently, in batches of 64 fibers, those that are not marked down first. The whole broadcast has the budget of handshake_timeout_ms, each connection gets at most the remaining time, and no new batch starts after abortAllRelays. A batch in flight still ends within one connect timeout. I checked it by hand, without adding a test: with 100 unroutable backends before 2 live ones and a 1 s connect timeout, both live backends got the request after 1 s, and a shutdown during a broadcast took 0.7 s. I did not add a regression test, because it would depend on wall-clock timing with unroutable addresses.
There was a problem hiding this comment.
[Blocker] The whole-broadcast budget still excludes name resolution. At programs/proxy/PostgreSQLFrontend.cpp:85, resolveAddress runs before the timed connect; programs/proxy/SocketIO.cpp:49-50 performs a blocking hostname lookup in ThreadModeScope, with no deadline. All 64 deliveries can queue onto the fixed blocking-worker pool, retain their original connect timeout, and continue resolving/connecting after the broadcast deadline or shutdown. The join at PostgreSQLFrontend.cpp:135-137 still waits for every delivery, while shutting down the client socket and aborting relays cannot cancel those lookups.
For example, on a four-worker proxy, 64 distinct backend names whose lookups each take five seconds require about 80 seconds of resolver work despite the default ten-second broadcast budget. Please make resolution and queued deliveries obey the shared deadline/shutdown state, rather than checking it only before starting a batch.
Conflict in `SecureSocketImpl::verifyPeerCertificateImpl`: master moved the loopback exemption after `X509_check_host` so that `isLocalHost` is only evaluated when the certificate does not name the host; this branch lets the caller supply `_peerIsLocalHost` instead of resolving. Keep both: the exemption is checked late, and uses `_peerIsLocalHost` when set.
Master enabled the `modernize-use-nodiscard` clang-tidy check, which failed the `arm_tidy` builds on the proxy sources. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110105&sha=ff5c604575f78d749966a17095c9c6c98b962ac7&name_0=PR&name_1=Build%20%28arm_tidy%2C%201%2F4%29 #110105 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…H` queries off the fiber stack Address review: the proxy and the backend could read one HTTP request differently, so that a request was routed by one user or query type and executed with another. - The request line must be `method SP request-target SP HTTP-version`: the server splits it at any whitespace and ignores what follows the version. - A line of the request head must end with CRLF and have a name without whitespace: the server takes ` X-ClickHouse-User: alice` for a field without a name. - `decompress` is the last occurrence parsed as a boolean, as `HTMLForm::getParsedLast<bool>`. - The only accepted `Transfer-Encoding` is a single `chunked`, `Content-Length` must be a plain number, and a chunk header is read as `HTTPChunkedReadBuffer` reads it. - A body without `Content-Length` and chunked encoding lasts until the end of the stream and is not inspected, so the query type is known only from the `query` parameter. - The formats are registered in the proxy, so a path such as `/db/table.CSV.gz` is parsed as by the server. - A `WITH` query is parsed on a thread of the global pool, where `checkStackSize` works: on the stack of a fiber, a deeply nested query of an unauthenticated client overflowed the stack. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Address review: only the `HandshakeResponse` of the client was bounded. The greeting and the authentication result of the backend and the auth-switch response of the client were read with the unbounded packet readers, which join continuation packets, so a faulty backend or an unauthenticated client could make the proxy allocate memory without a limit. Co-Authored-By: Claude Fable 5.2 <[email protected]>
…t at shutdown Address review: the unauthenticated request was delivered to every backend one by one, each unreachable backend costing a connect timeout, without a deadline, and shutdown waited for it. The backends now receive it concurrently, in batches of 64, those that are not marked down first. The whole broadcast has the time budget of a handshake and stops when the proxy shuts down. Co-Authored-By: Claude Fable 5.2 <[email protected]>
Address review: - When the backend closes its transport after EOF, the output already received from it is still delivered to a client whose window is closed: the backend leg is released and the client is polled until the output is written, instead of ending the session on the poll error. - The backend channel is released, and the pointers that the callbacks of the client channel use are cleared, before the client is polled for the end of the session: a packet of the client arriving during that wait used the freed backend channel. - libssh accepts data and repeated EOF after EOF, so the output saved in the EOF callback could grow without a bound. It is saved only for the first EOF, and a peer that sends data or EOF after EOF has its session ended. Co-Authored-By: Claude Fable 5.2 <[email protected]>
… a PostgreSQL `CancelRequest` Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
🕵 Merged master and addressed the 13 open review threads in separate commits:
All 15 proxy stateless tests pass locally on a release build, run one at a time. The previous CI run was red only because the review-threads gate skipped the full suite. Three threads stay open for a maintainer decision, as answered there: per-protocol backend health, the MySQL handshake thread ID, and MySQL |
# Conflicts: # programs/CMakeLists.txt
…or the style check The `catch_all` style check flagged the `catch (...)` around `parse<bool>` in `HTTPFrontend.cpp` as silently swallowing the exception. It does not: the failure is reported to the client as a bad request. Say so in a comment. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=110105&sha=3630733cba80d2d41b232d6d784b3a1758dc85c7&name_0=PR&name_1=Style%20check #110105 Co-Authored-By: Claude Fable 5.2 <[email protected]>
| static_cast<uint32_t>(std::min(sizeof(buffer), max_pending_output_bytes - out.bytes)), is_stderr); | ||
| if (read <= 0) | ||
| break; | ||
| forward(out, destination, buffer, read, is_stderr); |
There was a problem hiding this comment.
[Blocker] Preserve bytes when the source read invokes data callbacks
ssh_channel_read_nonblocking first polls its session and can invoke onBackendData or onClientData, which mutate this same PendingOutput. For example, with a closed destination window and out.bytes == max_pending_output_bytes - 1, an arriving two-byte packet queues one byte in its callback. The read then removes the remaining byte from libssh and returns it, but the queue is now full, so forward consumes zero. Ignoring its return value silently loses that byte. The reverse direction can lose client input the same way.
Reserve capacity across the callbacks, or retain every byte removed by the read even if callbacks filled the queue. Please cover new source data arriving during this read while the destination window is closed.
| AcceptState * raw = state.get(); | ||
| if (silk::FiberScheduler::run(acceptLoop, AcceptParams(raw->params), &raw->future) != 0) | ||
| throw Exception(ErrorCodes::SUPPORT_IS_DISABLED, "Cannot start the accept loop fiber"); | ||
| accept_states.push_back(std::move(state)); |
There was a problem hiding this comment.
[Blocker] Retain the accept-loop state before starting its fiber
This vector insertion can allocate after FiberScheduler::run has started the accept loop with &raw->future. If the insertion throws, the local state is destroyed, but the running fiber still holds that future's address. The pinned Silk implementation stores the raw future pointer and calls its set on completion; FiberFuture has no joining destructor. The loop also never enters accept_states, so stop cannot join it before destroying the scheduler. A startup allocation failure therefore becomes a use-after-free during cleanup.
Reserve the vector for every listener before scheduling any accept loop, or establish durable ownership before starting each fiber, with cleanup for a scheduling failure.
| auto [it, inserted] = seen.try_emplace(key); | ||
| if (inserted) | ||
| { | ||
| it->second.finished = std::make_shared<silk::FiberEvent>(); |
There was a problem hiding this comment.
[Blocker] Roll back first-seen state when setup or the hook throws
seen.try_emplace has already inserted an entry with done == false and a null finished. If this allocation throws, the connection handler catches the exception, but the incomplete entry stays in the router. Every later connection with the same target and name assigns the null event to wait_for, then repeats while (!finished) without waiting or yielding. Shutting down the client socket cannot interrupt this loop, so a transient allocation failure leaves permanent busy-spinning handlers and prevents proxy shutdown.
There is a second exceptional exit after the event is installed: runHook formats and logs its command before entering its try. If that throws, the entry retains an event that is never signaled, leaving subsequent connections suspended forever.
Allocate the event before publishing the entry, then guard the published state so every exceptional exit erases the unfinished entry and signals its waiters.
Implements a new application mode in the
clickhousebinary, namedproxy. The proxy accepts connections over end-user ClickHouse protocols, finds the upstream backend based on configurable rules (hostname from TLS SNI or HTTP header, user name, database name, and — for HTTP — query type), and forwards the traffic to it. It is built on thesilkfiber framework so that many concurrent connections are handled with low RAM usage.Start it with
clickhouse proxy --config-file proxy_config.xml; a fully commented example config is inprograms/proxy/proxy_config.xml, and the feature is documented atdocs/guides/oss/deployment-and-scaling/clickhouse-proxy.mdx.What it does
Hello, PostgreSQLStartupMessage, HTTP query type). MySQL is server-speaks-first with in-band TLS: when a rule needs the user or the database, the proxy terminates the handshake and rebinds authentication to the backend with an auth-switch; otherwise it is forwarded transparently. SSH is terminated and routed by the client's public key (which must be in a rule's allowlist and proven by signature), then re-originated to the backend with a bastion key whose host key is verified against aknown_hostsfile.ch-<tenant>to per-tenant backends).random,round_robin,least_connections,lowest_latency,least_resources) behind a common interface; a pool may list several backends for load balancing.session_id(from the HTTP URL) or by peer address, using a consistent (rendezvous) hash of the backends.least_resourcesstrategy; a JSON status endpoint,/ping, and static pages are served by the proxy itself.Validated end to end against a live server: HTTP
/ping, static pages, the status endpoint, GET/POST forwarding, the no-backend error paths, native protocol round-trips, and clean shutdown.Related: ClickHouse/silk#120 (the
spliceoperation this proxy relies on, sent tosilkupstream)Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a new
proxymode to theclickhousebinary: a lightweight, protocol-aware proxy that routes end-user connections (HTTP, native, MySQL, PostgreSQL, TLS-by-SNI, and raw TCP) to backend servers based on a configurable routing table, with TLS termination/passthrough, load balancing, health checks, and session stickiness.Documentation entry for user-facing changes
🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/110105]