English
Runtime and shards
crates/kernel/src/runtime.rs; ShardInfo, Handover, Plane, Sockets — crates/api/src/shard.rs; the balancer — crates/runtime/src/balance.rs.
Shards
Runtime::start(&Layout) starts layout.shards threads shard-<n> and builds a single-threaded tokio runtime in each. Layout is the configuration's runtime section (runtime) applied to the process CPU mask (Layout::of(options, allowed); the binary takes ours_net_sys::allowed_cpus() and the flags --cpus, --cpu-affinity, --shards): a CPU from the list outside the mask is a configuration error. With pin shard i is bound to cpus[i mod N], with none (the default) — to the whole cpus set; a failure is only a warning. Runtime::new(cpus) — a shard bound to each CPU, an empty list — one unbound shard (this is how tests run).
Runtime::apply(&Layout) on reload moves the running shards (sched_setaffinity by the thread's tid, remembered at start); the number of shards changes only with a restart — apply returns a warning.
Why this and not a work-stealing pool: every inbound opens a listening socket on every shard in one reuseport group, the OS kernel spreads connections by hash, and a connection lives on one shard from accept to close — without fighting over socket locks between cores. Distribution by SO_INCOMING_CPU is not used: without several NIC queues or RPS everything arrives on one CPU and would end up on one shard.
Every shard calls ours_bufpool::trim_thread() once a second (TRIM): the shard's buffer caches (take_vec, the relay, packet and h2 read pools) give back what was not needed during the past second. This way the memory taken by a load peak is returned 1–2 s after it, and under steady load the cache keeps as much as is needed.
Balancer
A hash spreads unevenly when there are few connections: four streams opened at once land on two shards as 2–2 only in three cases out of eight. So the shard that accepted a connection may hand it to another before it starts serving it (ours_runtime::balance, one mechanism for all):
- TCP inbounds (
vless,trojan,shadowtls,shadowsocks,http/mixed,anytls,socks,direct,tproxy) callbalance::spawn_accepted(stream, serve)instead oftokio::spawn; - QUIC inbounds (
hysteria,hysteria2,tuic) —balance::spawn(task)with a task that begins with theacceptof the connection: quinn drives a connection where it was accepted.
Every shard publishes a load estimate (atomics, read without locks; lower is better):
score = cpu + ACTIVE·(active + starting) + IDLE·idle + IN_FLIGHT·in_flightcpu— busyness in thousandths, an EWMA (a new sample with weight 1/4, a window of ~1 s). It is measured by one threadshard-loadevery 250 ms for all shards: withpin— the share of busy time of the shard's CPU from/proc/stat(user+nice+system+irq+softirq+steal over the total), withnone— the CPU time of the shard's thread (clock_gettimeon the thread clock). The cost is one read of/proc/stator oneclock_gettimeper shard per tick. With one shard the thread is not started.active— live relays (ours_relay) that transferred data in the current or the previous epoch (~1 s, the same thread advances the epochs): a relay holds abalance::Activity, compares the byte counter once per pass and on the first change in a new epoch increments that epoch's active counter; when closing, it subtracts itself from the epochs that still count (otherwise a batch of short connections that had just closed kept the shard "busy" for two more epochs and pushed the next batch to another shard).idle— live relays minus active ones.starting— connections handed to the shard that have not started relaying yet (handshake, dial): the start of a relay on the shard subtracts one. Only those handed over in the current and the previous epoch count — some connections never start a relay.in_flight— handed to the shard and not yet picked up by it.
The decision at accept (Balancer::choose): the shard compares itself with all shards (if there are no more than four) or with two random ones. Shards whose score is no worse than the best by more than HYSTERESIS are considered equal, and the connection goes to the one of them that got a connection the longest ago. A clearly better shard always takes the connection; among equals connections are handed out in turn — this way a batch of connections opened at once (iperf: a control connection + 4 data streams) is split evenly, even though by the score at accept time the control connection cannot be told from the data streams.
The driver of a multiplexed connection (HTTP/2 sessions of grpc, http, xhttp, on the server and on the client) is started through balance::spawn_movable(task) and may move to another shard even after it has started. The relay of the session's streams and their outgoing sockets stay on the shard where the connection was accepted (on the client — where the connection that needs the session was accepted); only the driver moves: the socket's TLS, encryption, parsing and assembling frames. This way one heavy stream occupies two cores: the driver on one, the relay on the other. The decision cannot be made when a stream opens: a stream becomes heavy later, when the shard scores taken at its start no longer apply.
- The
Movablewrapper measures the time the task spends inpolland every 500 ms (MOVE_WINDOW) asksBalancer::choose_away(own, home, share), whereshareis its share of the shard's time in thousandths. - A move happens only from an almost saturated shard (CPU ≥
MOVE_BUSY= 800 on average or by the last sample), only for tasks with a share ≥MOVE_SHARE= 200, only to the best of the compared shards and only if that one, with the task's load added, stays better than its own byHYSTERESIS:score_now(target) + share + HYSTERESIS < score_now(own).score_nowis the score with the CPU of the last sample if it is above the average: a shard on which a heavy stream has just started is busy right away, not after a second of averaging. When all shards are busy, the condition does not hold, and nothing moves; a task that takes almost the whole shard does not move either — it would carry the whole load over. - A move happens between two
polls: the wrapper hands the task's future over throughBalancer::hand(like a connection at accept, within_flightandplaced) and finishes the old task; the new one on the target shard registers itsWakerin everything it waits for on its very firstpoll. The sockets stay in the reactor of the original shard, which wakes the task across threads; the shard keeps running, so events get through. - A task remembers the shard where it was started (home). One that has moved away returns home as soon as its shard is saturated and home is not: the load that made it move has gone.
- New session streams are served next to the driver:
ours_transport_api::Connection::shardis the shard where the connection was created (for an HTTP/2 server — where the driver was running at that moment), andvless/trojanstart the stream handler throughbalance::spawn_at(shard, task). Otherwise, after a session moved, its new streams would pile up on the old shard next to the streams of other sessions; this way, with many streams, the layout converges to "a session and its streams on one shard", and only what has hit a core's limit gets spread. - The load accounts for itself: the monitor measures the CPU of every shard's thread.
runtime.stream_placement: localturns moves off (Balancer::set_spread, also applied on reload).
The cost of spreading is a cross-thread wakeup (eventfd) on every exchange between the driver and the relay, and buffers that one thread takes and another frees: ours-bufpool returns those to the cache of the thread that took them (bufpool), otherwise it would keep allocating and zeroing new pages.
Hand-over: TcpStream::into_std (take it off its own shard's reactor), the task into the receiving shard's channel (tokio::sync::mpsc, read by the task that Balancer::enter starts in the shard's thread), from_std and tokio::spawn there. While the task is in the channel, the receiver's in_flight is higher by 1. If the receiver has already stopped (the channel is closed), the task runs on the accepting shard; the descriptor belongs to the task and is closed together with it if it never runs.
Without shards (Balancer::enter was not called in this thread — tests, explain) both calls are just tokio::spawn.
Shard::enter(f) runs f with the shard's runtime as the current one: sockets are registered in its reactor, tokio::spawn starts tasks on it. This is how the kernel starts inbounds (on every shard), rule-sets, outbounds and Stage::commit (on the first).
Drop stops all shards and waits for the threads; unfinished tasks are dropped together with the runtime.
The binary's main thread keeps its own current-thread runtime only for signals, --watch, subscriptions and the Admin API (app/ours/src/main.rs).
ShardInfo
rust
pub struct ShardInfo { pub index: usize, pub count: usize, pub cpu: Option<usize>, pub owned: bool }cpu — the CPU the shard was bound to at start (None with cpu_affinity: none and without binding). owned — whether the inbound must take the address itself (true), or it will be handed this shard's sockets from the inbound it replaces on reload (false). Shard::owned()/Shard::handed() give the needed variant.
Socket hand-over (Handover)
Handover is one Plane per shard. A Plane stores, for every inbound ComponentId, its Sockets { tcp, udp } (OwnedFd). The protocol:
- At start an inbound puts copies of its listening sockets into
plane.keep(id, sockets). - Reload starts the successor with
owned = false; it takes the sockets withplane.take(id), starts accepting on them while the old one is still running, and puts them back intoplane.keep(id, …)— for the next reload, which will replace it in turn. - The old inbound is closed; its copies have already been handed over.
- For an inbound closed for good, the kernel calls
handover.release(id).
Why: closing all listeners and binding again means refusing connections in that window and losing packets already queued. Which inbounds get the sockets is decided by the kernel — Reload. Inbounds with keep/take: http (and mixed), trojan, shadowtls, shadowsocks, anytls and others (modules/protocols/*/src/inbound.rs).