The node manager
Source files: 34 · checked against Etemenanki 46c12e4 · katana v6.1.0
Etemenanki/supervisor/src/supervisor.rsEtemenanki/supervisor/src/policy.rsEtemenanki/supervisor/src/topology/spec_plan/plan.rsEtemenanki/supervisor/src/topology/spec_plan/inbound.rsEtemenanki/supervisor/src/build/users.rsEtemenanki/supervisor/src/build/apply.rsEtemenanki/supervisor/src/topology/inbound/mod.rsEtemenanki/supervisor/src/entity/session.rsEtemenanki/supervisor/src/track/mod.rsEtemenanki/supervisor/src/track/sampler.rsEtemenanki/supervisor/src/entity/usage.rsEtemenanki/supervisor/src/guard.rskatana/src/manager/node.rskatana/src/manager/mod.rskatana/src/runtime.rskatana/src/config.rskatana/src/main.rskatana/src/api/mod.rskatana/src/api/newv2board.rskatana/src/api/helium.rskatana/src/api/hysteria.rskatana/src/blocking.rskatana/src/lower/mod.rskatana/src/lower/inbound.rskatana/src/lower/outbound.rskatana/src/lower/route.rskatana/src/rule.rskatana/Cargo.lockkatana/tests/unit/e2e.rskatana/tests/unit/runtime.rskatana/tests/unit/rule.rskatana/tests/unit/manager/node.rskatana/tests/integration/sniff.rskatana/tests/support/mod.rs
Each running [[node]] is one NodeManager, running in one tokio task that the process root spawns. The manager is the node’s control loop. It asks the panel (or, for a locally described Hysteria 2 node, the config file) what the node should look like, lowers that answer into a spec, and has the node’s own Supervisor apply it. It also runs the node’s client-address task, reports each user’s traffic (and, to helium, the addresses users connected from) to the panel, and applies the config-file updates the process root sends on a hot reload.
This page is for contributors who change src/manager/. It covers the manager’s state and locks, run from the first bootstrap attempt to exit, the poll cycle, lowering off the runtime, how reconcile turns a panel answer into an apply and when it closes every session, what each kind of change does to live sessions, the static-update path, the client-address task, the report and the WireGuard warning. What a spec contains is on Lowering a node into a spec and Lowering inbounds and outbounds. How the supervisor plans and commits an apply is on Planning and applying a change.
Responsibilities
Section titled “Responsibilities”NodeManager owns:
- The node’s one supervisor. A
Supervisor<Uid>started by the first bootstrap attempt that succeeds and held in aOnceLockfor the rest of the task. Everything the node serves lives in it: the listener, the user table, the route table, the outbounds and the DNS resolvers. - The last panel answer (
Cur), which a poll falls back to when the panel answers 304 or fails. - What the supervisor runs (
Applied): the spec last applied and the node it was lowered from. Each new answer is compared against it. - The drop decision.
rebuild_pendingand the comparison of the node’s disruptive part (disruptive_part) decide when an apply is followed byclose(Selector::All). - The audit rules. The node’s
RuleManager, which holds the rules in force between a refresh and the lowering that reads them. - The client addresses. The client-address task, which records the users’ client addresses from the supervisor’s flow events where they are collected.
- Reporting. A
NodeReportat the end of every poll cycle and at exit. - Keeping the runtime free. Lowering, comparing and copying a spec, and dropping a replaced spec or user list, run on the blocking pool, because each grows with the node’s users.
- The panel client, which it replaces when a config edit changes a setting the client was built from.
It does not own:
- the panel HTTP protocol, ETags and user-record parsing. Those belong to the
PanelClientit holds; see Panel clients. Turning user records into supervisor credentials is part of lowering. - what a spec contains.
lower::node_specbuilds it; see Lowering a node into a spec. - node identity, respawn and the checks a reload runs before it touches a node.
src/runtime.rsdecides those; see Runtime and config reload. - serving, admission, sessions, routing, outbounds and byte counting. The supervisor does all of that; see Listeners and the serve loop, Users, principals and sessions, The plane: routing each flow and Tracking flows, stats and speed limits.
flowchart LR runtime["runtime::spawn_built"] nm["NodeManager::run (node task)"] api["PanelClient"] lower["lower::node_spec"] sup["Supervisor (Uid)"] ips["client-address task"] rules["RuleManager"] runtime -->|"StaticUpdate, token"| nm nm -->|"node_info, user_list, node_rule, report"| api nm -->|"update"| rules nm -->|"cfg, globals, answer, rules"| lower lower -->|"Spec"| nm nm -->|"start, apply_with, close, take_usage, sessions, shutdown"| sup sup -->|"FlowEvent::Opened"| ips ips -->|"client addresses"| nm rules -->|"rules()"| lower
One supervisor per node
Section titled “One supervisor per node”Each node lowers the process-wide [[outbound]] list and [dns] table (Globals) into its own spec, so each node builds its own outbound instances and its own resolvers; the [dns] comment in src/config.rs notes that each node keeps a cache of its own. A node’s bootstrap failure, its config edits and its shutdown go through its own supervisor only, and the other nodes’ listeners are not involved. Because each node builds its own outbounds, a WireGuard outbound that several nodes route to becomes one tunnel per node with the same key; see the WireGuard shared-outbound warning.
Key types
Section titled “Key types”NodeManager
Section titled “NodeManager”pub struct NodeManager { api: Mutex<Arc<PanelClient>>, cfg: Mutex<NodeConfig>, globals: Mutex<Arc<Globals>>, rules: RuleManager, supervisor: OnceLock<Supervisor<Uid>>, applied: Mutex<Option<Applied>>, rebuild_pending: AtomicBool, // … one more private field, used only by report collect_ips: AtomicBool, client_ips: Mutex<HashSet<(i64, IpAddr)>>, cur: tokio::sync::Mutex<Cur>,}
impl NodeManager { pub fn new(api: PanelClient, cfg: NodeConfig, globals: Arc<Globals>) -> Arc<Self>; pub async fn run( self: Arc<Self>, shutdown: CancellationToken, mut static_rx: mpsc::Receiver<StaticUpdate>, );
fn node_id(&self) -> u32; fn api(&self) -> Arc<PanelClient>; async fn bootstrap( &self, shutdown: &CancellationToken, static_rx: &mut mpsc::Receiver<StaticUpdate>, ) -> bool; async fn try_bootstrap(&self) -> Result<(), String>; async fn lower_off_runtime( &self, node: Node, users: Arc<[UserInfo]>, force: bool, ) -> std::io::Result<Lowered>; fn log_listening(&self, spec: &Spec<Uid>); fn log_clock_check(&self, spec: &Spec<Uid>); fn log_guard(&self, spec: &Spec<Uid>); fn spawn_client_ips(self: Arc<Self>, shutdown: CancellationToken) -> JoinHandle<()>; async fn serve( &self, shutdown: &CancellationToken, static_rx: &mut mpsc::Receiver<StaticUpdate>, ); fn poll_period(&self) -> Duration; async fn set_cur(&self, node: Option<Node>, users: Arc<[UserInfo]>); async fn node_info(&self) -> anyhow::Result<Option<Node>>; async fn poll_cycle(&self, rebuild: bool); async fn reconcile(&self, node: Node, users: Arc<[UserInfo]>); async fn apply_static(&self, u: StaticUpdate); async fn refresh_rules(&self); async fn report(&self); fn take_traffic(&self, supervisor: &Supervisor<Uid>) -> Vec<UserTraffic>; async fn take_client_ips(&self, supervisor: &Supervisor<Uid>) -> Vec<(i64, Vec<IpAddr>)>;}
fn disruptive_part(node: &Node) -> Node;fn collects_ips(api: &PanelClient, cfg: &NodeConfig) -> bool;fn vmess_clock_check(spec: &Spec<Uid>) -> bool;new cannot fail. It wraps the client in an Arc, and starts with an empty RuleManager, no supervisor, nothing applied, rebuild_pending false, no collected addresses and a default Cur. It sets collect_ips from collects_ips: true only when the client keeps_client_ips (helium) and controller.enable_device_limit is on, the setting that says the node sees its clients’ real addresses. The runtime calls it only after PanelClient::new and check_node have both accepted the [[node]] block (runtime::build_node). check_node checks what the node would run short of the panel’s answer: its real-IP, handoff and congestion keys, its outbounds, DNS and route table, and the listener of a newV2board Hysteria 2 node (lower::test_spec; see Lowering a node into a spec). node_id reads cfg.api.node_id, the number every log line of the node starts with. api clones the Arc<PanelClient> out of its lock, so a panel request never runs under the guard.
State and locks
Section titled “State and locks”Mutex is parking_lot::Mutex unless the table says otherwise. The struct’s doc comment gives the reason for the interior locks: the poll loop and the static updates run in one task, so the locks carry mutable state across &self methods on the shared Arc rather than arbitrate between tasks.
| Field | Type | Written by | Read by |
|---|---|---|---|
api |
Mutex<Arc<PanelClient>> |
new; apply_static for a Config update that builds a new client |
every panel call, through api(); apply_static (the old client for inherit_routes) |
cfg |
Mutex<NodeConfig> |
new; apply_static for Config |
node_id, poll_period (from bootstrap and serve), lower_off_runtime (which clones it), node_info, try_bootstrap and poll_cycle (disable_get_rule), take_traffic (disable_upload_traffic), apply_static (a clone of the old config, for the comparison with the edit) |
globals |
Mutex<Arc<Globals>> |
new; apply_static for Globals |
lower_off_runtime |
rules |
RuleManager, one parking_lot mutex inside |
refresh_rules (update) |
lower_off_runtime (rules()) |
supervisor |
OnceLock<Supervisor<Uid>> |
try_bootstrap, once |
spawn_client_ips, reconcile, apply_static, report, the exit steps of run |
applied |
Mutex<Option<Applied>> |
try_bootstrap, reconcile |
lower_off_runtime (an Arc of the running spec), reconcile |
collect_ips |
AtomicBool, Ordering::Relaxed |
new; apply_static for Config |
the client-address task, take_client_ips |
client_ips |
Mutex<HashSet<(i64, IpAddr)>> |
the client-address task (insert); take_client_ips (take); apply_static (clear, when collecting is turned off) |
take_client_ips |
rebuild_pending |
AtomicBool, Ordering::Relaxed |
set by poll_cycle(true) and by apply_static for Globals; cleared by try_bootstrap and by reconcile |
reconcile |
cur |
tokio::sync::Mutex<Cur> |
set_cur, from try_bootstrap and reconcile |
poll_cycle (the fallback), apply_static for Globals |
The node task runs its polls and its static updates one after the other, so it never waits on itself. The one other task that touches the manager is the client-address task. It holds an Arc<NodeManager>, reads collect_ips, records client addresses in client_ips, and reads the node id from cfg when it logs. Each is a short critical section with no I/O inside.
Three rules keep the locking correct:
- No
parking_lotguard across an.await. Every use is a short expression such asself.cfg.lock().controller.disable_get_rule, or a block that copies what it needs and ends before the next.await.reconcilecomputes its drop decision inside such a block and releasesappliedbefore it awaits the apply. The compiler enforces this:tokio::spawnrequires therunfuture to beSend, and aparking_lotguard isSendonly with parking_lot’s ownsend_guardfeature. katana’s dependency graph builds parking_lot with its default features only. curis held only to copy.poll_cycleandapply_statictake the tokio mutex, clone the node and theArcof the users out, and release it before they lower or call the panel.rebuild_pendingneeds no ordering. Only the node task reads or writes it, so program order is enough and every access isRelaxed.collect_ipsisRelaxedtoo: the client-address task may record one more address, or one fewer, around an edit that turns collecting on or off, and the edit clears what was collected.
Cur and Applied
Section titled “Cur and Applied”#[derive(Default)]struct Cur { node: Option<Node>, users: Arc<[UserInfo]>,}
struct Applied { node: Node, spec: Arc<Spec<Uid>>,}
enum Lowered { Unchanged, Changed { spec: Arc<Spec<Uid>>, owned: Box<Spec<Uid>> },}Curis the panel’s last answer, the value a poll uses in place of a 304 or a failed request.try_bootstrapstores the first answer, andreconcilestores every answer it is handed.Cur::nodeisNoneonly until the first attempt succeeds.Appliedis what the supervisor runs.try_bootstrapstores the spec the supervisor started with, andreconcilereplaces it after each apply that committed.Applied::nodeis the reference for the comparison of disruptive parts, andApplied::specfor the “nothing changed” shortcut.Nodeisapi::Node, the contract’sNodeConfig(see Panel clients).Loweredis whatlower_off_runtimereturns:Unchangedwhen the new spec equals the running one, or the new spec twice, once shared forAppliedand once owned for the supervisor to take.
The users and the spec are shared rather than copied, because a node can list tens of thousands of users. A replaced Cur::users or Applied, and a spec an apply refused, are dropped on the blocking pool (blocking::drop_off_runtime), since freeing them is work that grows with the users too.
StaticUpdate
Section titled “StaticUpdate”pub enum StaticUpdate { Config(Box<NodeConfig>), Globals(Arc<Globals>),}src/manager/mod.rs holds only this enum and re-exports NodeManager. The runtime sends updates over a bounded mpsc channel of capacity 16, created per node in runtime::spawn_built. Its send().await waits when the channel is full, and the node drains it both while it waits between bootstrap attempts and in its steady state.
Configcarries this node’s new[[node]]block. The runtime sends it only when the block changed and the node’s identity did not; an identity change is a remove and an add instead. It may changepanel_type,[node.api]fields,enable_mtlsor[node.hysteria], which the panel client was built from, and the node rebuilds its client for those.Globalscarries the new process-wide[[outbound]]list and[dns]table. The runtime sends it to every running node whenever either changed.
The identity tuple, the checks the runtime runs before it sends anything, and the order in which it removes, reconfigures and adds nodes are on Runtime and config reload.
What the manager asks of the supervisor
Section titled “What the manager asks of the supervisor”| Call | Where | Notes |
|---|---|---|
Supervisor::start(*owned) |
try_bootstrap, once |
The builder’s defaults: first apply with ApplyOptions::default(), sampler tick DEFAULT_SAMPLE_INTERVAL (1 s), no usage sink, default socket options. The returned ApplyReport is discarded. |
apply_with(*owned, ApplyOptions { allow_disruptive: true }) |
reconcile |
Every later change is a whole-spec apply. katana never uses set_users, upsert_user, remove_user or update. The ApplyReport is discarded too, including its restarted list (the inbound a Disrupt step ended) and its removed list (the inbounds whose sessions CloseSessions closed); katana works out whether the bind moved on its own (see Reconcile). |
close(Selector::All) |
reconcile, after an apply that committed with drop_all |
The count it returns is discarded. |
tracker().subscribe() |
spawn_client_ips, once |
A broadcast::Receiver<FlowEvent> on a channel of EVENT_CAPACITY (1024) events. |
take_usage() |
take_traffic |
katana takes usage when it reports; it registers no UsageSink. |
sessions() |
take_client_ips |
Each live session’s user and source address, for the addresses of connections still open. Only where addresses are collected. |
shutdown(Duration::ZERO) |
run, at exit |
Zero grace: stop accepting and close whatever is left at once. |
The spec also carries the node’s Policies, built from [node.controller]; the supervisor takes them at every commit (Guard::set_policy). The only Step::Disrupt a katana spec can lead to is a Hysteria 2 obfuscation change on the same bind, from the panel or from [node.hysteria] on a locally described node: katana lowers no TUN inbound, the other source of Disrupt. Without allow_disruptive the supervisor would refuse such an apply with ApplyError::Disruptive. katana closes every session for that change anyway (see the effect of each change).
Constants
Section titled “Constants”| Constant | Value | Where |
|---|---|---|
BOOTSTRAP_RETRY_MIN |
1 s | src/manager/node.rs |
BOOTSTRAP_RETRY_MAX |
60 s | src/manager/node.rs |
USER_SET |
"users", the tag of the node’s one user set |
src/lower/mod.rs |
AUDIT_TAG_PREFIX |
"audit#", the prefix of every audit outbound’s tag |
src/rule.rs |
Lifecycle of run
Section titled “Lifecycle of run”if self.bootstrap(&shutdown, &mut static_rx).await { let watch = self.clone().spawn_client_ips(shutdown.clone()); self.serve(&shutdown, &mut static_rx).await; let _ = watch.await;}if let Some(supervisor) = self.supervisor.get() { supervisor.shutdown(Duration::ZERO).await;}self.report().await;run has three phases. bootstrap brings the node up, retrying until it is up or the token is cancelled, and returns whether it came up. The client-address task and serve, the steady-state loop, run only after a successful bootstrap. The exit steps run in both cases. They test the OnceLock rather than the bootstrap result, so a supervisor that started in an attempt the token then cut short is still shut down.
sequenceDiagram
participant RT as runtime
participant NM as node task
participant P as PanelClient
participant S as Supervisor
participant A as client-address task
RT->>NM: spawn run(shutdown, static_rx)
loop bootstrap, until up or cancelled
NM->>P: forget_etags, node_info, user_list, node_rule
NM->>S: Supervisor::start(lowered spec)
end
NM->>A: spawn_client_ips, subscribed to the tracker
loop serve, until cancelled
alt interval tick
NM->>P: node_info, user_list, node_rule
NM->>S: apply_with, then close(All) if drop_all
NM->>S: take_usage, sessions
NM->>P: report
else static update
NM->>NM: apply_static
end
end
NM->>A: await, it stops on the same token
NM->>S: shutdown(Duration::ZERO), take_usage
NM->>P: final report
Bootstrap
Section titled “Bootstrap”bootstrap calls try_bootstrap until one attempt succeeds. One attempt runs these steps and stops at the first that fails:
- Fresh reads.
api().forget_etags()clears the client’s ETag cache, so each attempt reads the node and users in full. - Node description.
node_info()returns the panel’s answer, or the local description for a Hysteria 2 node whose[node.hysteria].portis non-zero (next section). - Users.
api().user_list()must return a list; the attempt fails without one. The code comment calls the list required, not best-effort: a node up without its users serves nobody. - Rules.
refresh_rules(), unlesscontroller.disable_get_ruleis set. It runs before lowering so the first spec already carries the audit routes. A rules request that fails only logs a warning (seerefresh_rules) and does not fail the attempt. - Lowering.
lower_off_runtime(node, users, true)builds the spec from the current config, globals and rules on the blocking pool. It is forced, so it never comes backUnchanged. - Start.
Supervisor::start(*owned)validates the spec, builds everything, binds the listener and commits. A port still held by another process fails here. - State.
let _ = self.supervisor.set(supervisor)stores the supervisor; the result is ignored because the lock is always empty here, sincebootstrapstops at the first success. Thenlog_listeninglogs the bound address and any handoff socket,log_clock_checksays so when a VMess node’s clock check is off,log_guardlogs how failed authentications are handled,appliedbecomes{ node, spec },rebuild_pendingis cleared, andset_cur(Some(node), users)stores the answer.
Supervisor::start is the last step that can fail. A start that fails returns an error before the OnceLock is set, so the next attempt starts from nothing. Every step after it cannot fail, and there is no .await between start returning and the OnceLock being set.
An attempt fails with one of these reasons:
| Condition | Reason |
|---|---|
node_info returns Ok(None) |
panel returned no node info |
node_info returns Err |
node_info failed: <error> |
user_list returns Ok(None) |
panel returned no user list |
user_list returns Err |
user_list failed: <error> |
lower_off_runtime returns Err |
initial start failed: <error> |
Supervisor::start returns Err |
initial start failed: <error> |
A panel error is rendered with {e}, which prints its outermost context only, for example GET /api/v1/server/UniProxy/config. A UniProxy config answer katana cannot serve is refused as the client reads it, and that outermost message carries the reason: parse UniProxy config response: <reason>. A failed bind reads as the supervisor’s ApplyError::Bind, for example initial start failed: inbound <tag>: binding <bind> failed: <os error>.
After a failure, bootstrap logs at error:
node <id>: <reason>; retrying in <n>sfor example node 1: node_info failed: GET /api/v1/server/UniProxy/config; retrying in 1s, or, for an answer asking for what katana cannot serve, node 1: node_info failed: parse UniProxy config response: node requests kernel-unsupported feature: httpupgrade transport; retrying in 1s. The wait starts at BOOTSTRAP_RETRY_MIN (1 s) and doubles after each failure up to BOOTSTRAP_RETRY_MAX (60 s). Each wait is also capped at the poll period (poll_period()), so a node that syncs every few seconds also retries every few seconds. With the default update_periodic of 60 s the waits are 1, 2, 4, 8, 16, 32 and then 60 seconds. The code comment gives the reason for retrying at all: what stops a first attempt is usually transient (the panel is restarting, DNS is not answering yet, the port is still held by the process this one replaces), and giving up would leave the node dark until katana restarts.
Each wait is one tokio::time::sleep, created and pinned once, so updates that arrive during it cannot push the retry back. While it waits, the node applies static updates as they arrive, which also keeps the runtime’s bounded channel from filling:
- A
Globalsupdate stores the new globals and setsrebuild_pending. There is no supervisor to reconcile, and a successful attempt clears the flag again, because the supervisor it starts is already built from the new globals. - A
Configupdate is applied or refused (seeStaticUpdate::Config) and ends the wait at once, because the edit may be the fix. With no supervisor it only stores the new config and client, and the next attempt reads with the new client and builds from the new config. The next wait still doubles.
The attempt and the wait each sit in a biased select! whose first branch is the cancellation token, so a node cancelled while it is still coming up returns false at once and drops any panel request or bind in flight. While a node is in this loop it serves nothing on its port; the process and the other nodes are not affected.
The node description
Section titled “The node description”node_info returns anyhow::Result<Option<Node>> with the panel client’s meaning: Ok(Some) is an answer, Ok(None) is 304 Not Modified, Err is a failed request or an answer the client refused. It reads api.node_type and [node.hysteria] from the current cfg on every call. When the node type parses as NodeType::Hysteria2 (hysteria2, hysteria or hy2, in any case) and hysteria.port is not 0, it returns api::hysteria::local(&cfg.hysteria, port) and never asks the panel. That function (src/api/hysteria.rs) builds the contract’s Hysteria2 node from [node.hysteria] alone: its port, obfuscation, UDP relay, masquerade and rates; see Panel clients. A helium node never takes this path. The doc comment: “A helium node is never local: its panel describes the protocol, and its client refuses a node_type and a [node.hysteria].port.” Its node_type is empty, so the check fails and the panel is asked.
With hysteria.port == 0 a Hysteria 2 node asks the panel like every other node type. On newV2board the UniProxy client builds the node with api::hysteria::uniproxy: the port, obfuscation and rates from the panel’s answer, the rates overridden by [node.hysteria] where it sets them, and the UDP relay and masquerade, which UniProxy has no field for, from [node.hysteria]. helium’s answer describes all of it, and leaves only the congestion control to [node.hysteria]. Either way lower_hysteria reads the obfuscation, rates, UDP relay and masquerade from the node, and only the credential kind and the congestion control from [node.hysteria]; on helium the credential kind keeps its default (Lowering inbounds and outbounds). The user list always comes from the panel. The local path never returns Ok(None). It returns Err only when api::hysteria::local refuses the block, which the node check (lower::test_spec) has already run before the node was built and before the runtime sent the edit, so a locally described node does not fall back to Cur::node in poll_cycle.
The steady-state loop
Section titled “The steady-state loop”fn poll_period(&self) -> Duration { Duration::from_secs(self.cfg.lock().controller.update_periodic.max(1))}update_periodic defaults to 60 seconds (default_update_periodic in src/config.rs) and is clamped to at least 1 second. serve builds a tokio::time::interval of that period and immediately awaits its first tick, which an interval completes at once, so the first poll_cycle runs one full period after bootstrap, not straight after it.
loop { tokio::select! { _ = shutdown.cancelled() => break, _ = interval.tick() => self.poll_cycle(false).await, Some(update) = static_rx.recv() => { self.apply_static(update).await; let new_period = self.poll_period(); if new_period != period { period = new_period; interval = tokio::time::interval(period); interval.tick().await; } } }}- Polls and static updates are strictly serialized. A static update that arrives during a poll waits for the poll to finish, and the other way round.
- After each static update the loop recomputes the period. When
update_periodicchanged, it replaces the interval and again consumes the immediate tick, so the next poll comes one new period after the update. - If every sender is dropped,
recv()yieldsNone, theSome(update)pattern does not match andselect!disables that branch for that iteration. The loop keeps polling. - The
select!is not biased: when several branches are ready at once, tokio picks one at random. Cancellation is observed only between iterations (see cancellation).
The poll cycle
Section titled “The poll cycle”async fn poll_cycle(&self, rebuild: bool)The timer calls it with rebuild = false. apply_static calls it once, straight after a config edit, with rebuild = true when the edit changed something only the config file can show. Each call runs these steps in order, whatever the earlier ones returned:
| Step | Call | On Ok(None) (304) |
On Err |
|---|---|---|---|
| 0 | rebuild_pending = true, only when rebuild |
||
| 1 | node_info() |
use Cur::node |
log node <id>: node_info: <error> at warn, use Cur::node; a UniProxy answer the client refuses is such an error, for example node 1: node_info: parse UniProxy config response: tcp header is not an object |
| 2 | api().user_list() |
use Cur::users |
log node <id>: user_list: <error> at warn, use Cur::users |
| 3 | refresh_rules(), unless disable_get_rule |
keep the rules | log at warn, keep the rules |
| 4 | reconcile(node, users) |
||
| 5 | report() |
log at warn |
The panel requests run one after the other, each bounded by the client’s timeout: api.timeout seconds, or 5 when it is 0 (ApiConfig::timeout_secs). Treating a 304 and a failed request the same way, as “use the last answer”, is what lets a flaky panel leave a running node alone: a poll that learns nothing new hands reconcile the same node and users again.
The rules are refreshed before reconcile, so a changed rule set is lowered in the same cycle.
The fallback reads Cur::node with .expect("node_info present after bootstrap"). It holds because serve runs only after bootstrap returned true, which happens only after try_bootstrap ran set_cur(Some(node), …); reconcile also passes Some; and apply_static runs a poll cycle only when the supervisor is set, which is the same condition.
Lowering off the runtime
Section titled “Lowering off the runtime”async fn lower_off_runtime(&self, node: Node, users: Arc<[UserInfo]>, force: bool) -> std::io::Result<Lowered>lower_off_runtime clones the config, the globals, the rule list and an Arc of the running spec out of their locks, then hands the work to the blocking pool through blocking::off_runtime: it lowers the spec, returns Unchanged when force is unset and the spec equals the running one (dropping the new one there), and otherwise returns it with the owned copy the supervisor takes. All of this grows with the user count. On a runtime worker it would hold the worker long enough to leave the I/O driver unpolled, because tokio does not hand the driver to a parked worker before running the task it woke, and every connection in the process would wait, not just the node’s. lowering_leaves_the_runtime_worker_free pins this with 200 000 users on a one-worker runtime.
What a poll feeds into lowering
Section titled “What a poll feeds into lowering”On the blocking pool, lower_off_runtime calls:
pub fn node_spec( cfg: &NodeConfig, globals: &Globals, node: &Node, users: &[UserInfo], audit: &[DetectRule],) -> io::Result<Spec<Uid>>;| Input | Where the manager gets it | What it becomes in the spec |
|---|---|---|
node |
the panel’s answer, the local Hysteria 2 description, or Cur::node |
The inbound: its BindSpec (Tcp, or Udp for Hysteria 2) on bind_host(listen_ip) and node.port(), its tag Type_listenip_port, its protocol, transport and security. |
users |
the panel’s list or Cur::users |
The user set users: one UserSpec per admitted user keyed by Uid(uid), with the credential the protocol reads, the user’s own speed_limit (0 for none), which the client has already replaced with api.speed_limit when that is set, and, under enable_device_limit, the user’s device_limit. |
audit |
RuleManager::rules(), refreshed immediately before |
One audit#<id> blackhole outbound and one route rule per rule id, ahead of the node’s own rules. |
cfg |
a clone of NodeConfig |
[node.route] (default outbound direct), listen_ip, the certificate and key (read from disk on every lowering that needs them), disable_sniffing, disable_vmess_clock_check, real_ip_header and real_ip_from (a WebSocket node’s real_ip), handoff_dir and handoff_group (a stream node’s handoff socket, with the group’s gid read from /etc/group on every lowering), [node.hysteria]’s credential and congestion, and the policies: enable_device_limit, the ban_* settings and carrier_max_failures. |
globals |
Globals |
The built-in direct, block, freedom and blackhole outbounds, every [[outbound]], and [dns]. |
The spec’s policies come from [node.controller]: ip_ban is set only under enable_device_limit with a non-zero ban_max_failures, and carrier_max_failures whenever it is non-zero. The spec has no balancers. The inbound’s user_removal and every outbound’s drain are None, so the supervisor-wide defaults apply: UserRemovalPolicy::Close and DrainPolicy::Keep (see Planning and applying a change). How each piece is built, and what lowering refuses by name, is on Lowering a node into a spec, Lowering inbounds and outbounds and Destination audit.
Reconcile
Section titled “Reconcile”async fn reconcile(&self, node: Node, users: Arc<[UserInfo]>)reconcile turns one answer into at most one apply and at most one close:
-
set_cur(Some(node), users)stores the answer. -
Without a supervisor it returns. (It is never called without one:
poll_cycleruns after bootstrap, andapply_staticchecks first.) -
Under the
appliedlock, read with.expect("applied once the node is up"), which holds for the same reason, it computessrc/manager/node.rs let drop_all = self.rebuild_pending.load(Ordering::Relaxed)|| disruptive_part(&node) != disruptive_part(&applied.node); -
lower_off_runtime(node, users, drop_all)builds the spec. Whendrop_allis false and the new spec equalsapplied.spec, it comes backUnchangedandreconcilereturns without calling the supervisor. A spec that does not lower is logged asnode <id>: cannot build the node, keeping the running one: <error>aterror. A UniProxy answer katana cannot serve never gets this far: the client refuses it innode_info. -
It computes
rebound(the binds of the new spec’s first inbound, its own and its handoff socket asInboundSpec::bindsyields them, differ from the applied spec’s),clock_turned(the VMess clock check differs,vmess_clock_check) andguard_changed(the policies differ). -
supervisor.apply_with(*owned, ApplyOptions { allow_disruptive: true }). A refused apply is logged asnode <id>: apply failed, keeping the running one: <error>aterror, and the new spec is dropped on the blocking pool. -
When the apply committed and
drop_allis set,supervisor.close(Selector::All), thenrebuild_pendingis cleared. -
When
reboundis set,log_listeninglogs the new address and handoff socket; whenclock_turnedis set,log_clock_checklogs the new state; whenguard_changedis set,log_guardlogs the new policies. -
appliedbecomes{ node, spec }, and the one it replaces is dropped on the blocking pool.
flowchart TB
start["reconcile(node, users)"]
cur["set_cur: store the answer"]
drop{"drop_all?"}
low["lower_off_runtime, not forced"]
force["lower_off_runtime, forced"]
same{"Unchanged?"}
done["return, no supervisor call"]
apply["apply_with, allow_disruptive"]
drop2{"drop_all?"}
close["close(Selector::All), clear rebuild_pending"]
log["log the bind, clock check or policies if changed"]
store["applied = node and spec"]
start --> cur --> drop
drop -->|no| low --> same
same -->|yes| done
same -->|no| apply
drop -->|yes| force --> apply
apply -->|"committed"| drop2
drop2 -->|yes| close --> log
drop2 -->|no| log
log --> store
Details that constrain changes to this code:
drop_allis decided before the spec comparison. It forces the lowering, so an edit that lowers to the same spec still closes every session when it setrebuild_pending.route_change_drops_connectionsdepends on this: its edit setsroute.default = "direct", whichlower_routealso produces for an unsetdefault, so the lowered route table is identical, and the connection must drop all the same.- The close comes after the commit. The supervisor has already swapped in the new handler, route table and outbounds when
close(Selector::All)runs, so a client that reconnects straight away reaches the new configuration. The close takes every session the supervisor tracks at that moment, including any the new handler accepted between the commit and the close. rebuild_pendingis cleared by the close that follows a committed apply, or by a successful bootstrap.reboundis computed by katana.ApplyReport::reboundlists only an inbound that kept its tag while its bind or its handoff socket moved, not one whose handoff socket was added, and a katana inbound’s tag carries its port (Type_listenip_port), so a port change is a new tag and would not show there. katana compares the whole list of binds, so a handoff socket added, moved or removed logs the line as well.log_listeningprints the address bound, not the one configured. It reads the first inbound’sBindSpec, logs only aTcporUdpbind (the only kinds katana lowers), and formats an IP host as aSocketAddr, solisten_ip = "0.0.0.0"on a host whose IPv6 sockets also take IPv4 logsnode <id>: listening on [::]:<port>atinfo. A host that is not an IP literal is printed as<host>:<port>. When the inbound has a handoff socket, the line goes on, and for handed-over connections on <path>. It runs at bootstrap and after every apply that changed a bind.- The clock check and the policies are logged when they change.
log_clock_checklogsnode <id>: VMess clock check off(oron) atinfo, at bootstrap only when it is off, and after any apply that turns it.log_guardlogs atinfoat bootstrap and after an apply that changed the policies: by defaultnode <id>: device limit off, no IP ban; gRPC connections closed after 8 failed streams in a row, and withenable_device_limiton and the other settings at their defaultsnode <id>: device limit on, IP ban after 30 failures in 120s for 300s; gRPC connections closed after 8 failed streams in a row.
Why katana closes every session itself
Section titled “Why katana closes every session itself”The supervisor keeps what an apply leaves in place: a swapped handler serves only new connections, and a route change does not move a flow that is already routed (see Planning and applying a change). katana’s rule is stronger. The module comment names it: what must drop every connection is a route, outbound or DNS edit, or the panel changing the node’s protocol or transport, and the node closes those out itself after the apply commits. route_change_drops_connections calls it a business requirement. The two sources of drop_all are:
rebuild_pending, for a change the panel’s answer cannot show: a local config edit (poll_cycle(true)) or aGlobalsupdate.disruptive_partof the new node against that ofApplied::node, for a change the panel made.disruptive_partis the node with what the supervisor applies to new connections alone reset: an AnyTLS node’spadding_schemeset toNone, and a Hysteria 2 node’sup_mbpsanddown_mbpsset to 0,ignore_client_bandwidthtotrueand the UDP idle timeout to 0. Every other field of the node counts: the protocol, the port, the transport and its settings, the security, REALITY’s key, shortId and cover site, a Shadowsocks cipher and key, the VLESS flow, an sss node’s chains and datagram limit, and a Hysteria 2 node’s obfuscation, masquerade and whether it relays UDP. A new padding scheme reaches the sessions that start after it, and new rates or a new idle timeout the connections that arrive after it. The users are not part of the node, so a speed limit is not compared here either. A UniProxy field the client does not read cannot change the node, so a newhostorserver_nameon a Trojan, Hysteria 2 or AnyTLS node drops nothing.
The doc comment of disruptive_part gives the reason for UDP: “Whether it relays UDP at all does drop them: turned off, it would go on relaying for every client connected before, for as long as its connection lasts; turned on, they would go on being refused.” Its test gives the reasons for two more: “A new masquerade, or none, shows a prober another face: one kept connection would go on answering the old way”, and “sss’s chains are the protocol’s: a client holding the old ones decodes nothing the new ones send.” A new obfuscation key, REALITY key, shortId or cover site locks out a client holding the old ones. The supervisor, for its part, plans an obfuscation change on the same bind as a Step::Disrupt with the reason the hysteria2 obfuscation changed; connected clients cannot follow the new key.
The supervisor keys each inbound’s admissions by the inbound’s tag (admit in supervisor/src/build/users.rs). A user keeps their principal, and with it their sessions, while the same inbound admits them by the same credential, even when the inbound’s protocol changed. A V2ray node that its panel switches between VMess and VLESS (on helium, the config answer’s protocol) keeps its tag V2ray_<listen_ip>_<port>, and both protocols read a UUID, so without katana’s close its users’ sessions would run on under the old handler. On newV2board the switch is an enable_vless edit, which changes the node’s identity, so the runtime respawns the node instead. A port change gives the inbound a new tag on a new bind, so every user is admitted afresh under a new principal, and the old tag’s sessions go through CloseSessions.
The effect of each change
Section titled “The effect of each change”| Change | Arrives through | drop_all |
What the supervisor plans | Live sessions |
|---|---|---|---|---|
| A user added, removed, or given a new credential | a poll (user_list) |
no | Build(UserSet); the principals of removed users and of changed credentials revoked |
Unchanged users keep their principal and their sessions. Revoked principals are handled by UserRemovalPolicy::Close, the default. |
Only a speed limit: a user’s, or the api.speed_limit override the client applies |
a poll, or a Config edit that builds a new client |
no | Build(UserSet) with the same principals and credentials, so the listener’s user table is kept; at commit publish_limits sets the new rate on each user’s pacer |
Kept. Live flows are paced at the new rate from their next read or write after the commit. |
Only a device limit: the panel’s, or enable_device_limit turned on or off |
a poll, or a Config edit |
no | Build(UserSet) with the same principals; at commit publish_limits sets each user’s device limit |
Kept. A lowered limit closes no session; it refuses new sessions from further addresses. |
The policies: enable_device_limit, a ban_* setting or carrier_max_failures |
a Config edit, then poll_cycle(false) |
no | the new Policies, taken at commit by Guard::set_policy; turning bans off lifts every ban |
Kept. The new policies apply to what happens next. |
disable_vmess_clock_check |
a Config edit, then poll_cycle(false) |
no | Build(Inbound) and SwapHandler on the same listener |
Kept, on the handler they were accepted with. |
A WebSocket node’s real_ip_header or real_ip_from |
a Config edit, then poll_cycle(false) |
no | Build(Inbound) and SwapHandler on the same listener |
Kept, on the handler they were accepted with. New connections take their client from the new header and networks. |
handoff_dir or handoff_group on a stream node |
a Config edit, then poll_cycle(false) |
no | Build(Inbound) and SwapHandler on the TCP listener; Bind of the new handoff socket in prepare and StopAccepting of the old one, or only one of the two when the socket is added or removed; a new socket joins the caps of the TCP listener the inbound keeps |
Kept, handed-over ones included. New connections are handed over on the new socket. |
A Hysteria 2 node’s rates (up_mbps, down_mbps, ignore_client_bandwidth) or helium’s UDP idle timeout, from the panel |
a poll | no | Build(Inbound) and SwapHandler on the same bind |
Kept, at the rate and timeout they started with. New connections get the new values. |
| helium’s Hysteria 2 masquerade, or its UDP relay turned on or off | a poll | yes | SwapHandler on the same bind |
All closed by close(Selector::All). |
| An AnyTLS node’s padding scheme from the panel | a poll | no | Build(Inbound) and SwapHandler on the same listener |
Kept, on the handler they were accepted with. Sessions that start after it get the new scheme. |
| The audit rules | refresh_rules in a poll, or a rule_list_path edit |
no | New audit#<id> outbounds built, removed ones drained under DrainPolicy::Keep, Build(Route), PublishPlane; every other outbound reused |
Kept. New flows are routed by the new table. |
| A certificate or key file whose content changed at the same path | the next lowering, which reads both files | no | Build(Inbound) and SwapHandler on the same listener |
Kept, on the handler they were accepted with. New connections get the new certificate. |
| Any other part of the panel’s node: the protocol, port, transport, security, REALITY’s settings, a cipher or key, the VLESS flow, an sss node’s chains or datagram limit | a poll | yes | The plan for the changed inbound: SwapHandler on the same bind, or, when the bind moved (a new port, or a switch between Hysteria 2 and a stream type), Bind of the new one in prepare and StopAccepting of the old one |
All closed by close(Selector::All). |
| A Hysteria 2 obfuscation change | a poll, or a [node.hysteria] edit on a locally described node |
yes | SwapHandler plus Step::Disrupt, allowed by allow_disruptive |
All closed. |
A local rebuild edit: route, controller.listen_ip, controller.cert, controller.disable_sniffing or any [node.hysteria] field, the rate overrides and congestion included (on helium, congestion is the only one of these [node.hysteria] fields it can set) |
StaticUpdate::Config, then poll_cycle(true); a [node.hysteria] edit also builds a new client |
yes, through rebuild_pending |
whatever the new spec needs | All closed. |
An [[outbound]] or [dns] edit |
StaticUpdate::Globals, then reconcile with Cur |
yes, through rebuild_pending |
Changed outbounds built as new versions; a DNS change rebuilds the resolvers and every outbound that holds them, which is every outbound except the blackholes (block, blackhole and the audit# outbounds); PublishPlane |
All closed, on every node. |
| Nothing | a poll | no | no call: the spec equals applied.spec |
Untouched. |
A change that combines several rows takes the strongest one: any drop_all source closes every session once the apply commits.
The plan column names steps, not their order. A plan lists them as the DNS, outbound, balancer, route and user-set Build or Reuse steps, then each inbound’s Bind, Build or Reuse, then PublishPlane, then SwapHandler and Disrupt, then StopAccepting, CloseSessions and Drain. Prepare does everything fallible and commit the rest; see Planning and applying a change. Sessions, principals and revocation are on Users, principals and sessions, and pacing on Tracking flows, stats and speed limits.
Static updates
Section titled “Static updates”async fn apply_static(&self, u: StaticUpdate)StaticUpdate::Config
Section titled “StaticUpdate::Config”A config edit is taken whole or not at all. apply_static first builds what the edit needs, then stores it, then applies it with one poll cycle:
flowchart TB
u["StaticUpdate::Config(new)"]
c{"panel_type, api, enable_mtls or hysteria changed?"}
n["PanelClient::new(new), inherit_routes"]
r["refused: log, store nothing"]
s["store cfg and client"]
q{"supervisor up, and resync?"}
p["poll_cycle(rebuild)"]
k["stored, read where used"]
u --> c
c -->|yes| n
c -->|no| s
n -->|Err| r
n -->|Ok| s
s --> q
q -->|yes| p
q -->|no| k
- Client.
apply_staticclones the old config out of its lock (let old = { self.cfg.lock().clone() };). Whenpanel_type, any[node.api]field (ApiConfigcompares every field),enable_mtlsor anything in[node.hysteria]differs,PanelClient::newbuilds a client from the new block. The client copies settings at construction (the node type, VLESS, the speed override, the rule file, the timeout,enable_mtls, and on newV2board the[node.hysteria]block it completes a Hysteria 2 node with), so without a new one the node would keep answering to the old values. The new client callsinherit_routeson the old one: a newV2board client takes over the routes the old one last read, so the audit rules derived from theirblockentries hold until the new client reads the node config itself. helium sends no routes and inherits nothing: its audit rules are the local rule list alone. - Refusal. If
PanelClient::newfails, the manager logsnode <id>: config edit refused, keeping the running one: <error>aterrorand returns. Nothing from the edit is stored, including fields that needed no build. The runtime has already built a client from the same block before it sent the update (runtime::apply_reload), so this is a backstop. A helium block that sets[node.api]node_typeorenable_vless, or any[node.hysteria]key butcongestion, is such a block:helium::Client::newrefuses it, so the start,--testand the reload that would carry it all refuse it before any node sees it. - Rebuild.
rebuildis set whenroute,controller.listen_ip,controller.cert,controller.disable_sniffingor anything in[node.hysteria]differs (old.hysteria != new_cfg.hysteria; on helium, whose client refuses every other key of the block, that is acongestionedit). The listener or its routes are built from these local settings, and the panel’s answer does not change when they do.rehandleis set whencontroller.disable_vmess_clock_check,real_ip_headerorreal_ip_fromdiffers, or any ofenable_device_limit,ban_max_failures,ban_window_secs,ban_secsandcarrier_max_failures: only the inbound’s handler, the users’ limits and the policies are built from these, and the apply serves new connections with them and leaves the running ones be.rebindis set whencontroller.handoff_dirorcontroller.handoff_groupdiffers. The code comment gives the reason it needs no rebuild: “A handoff socket is a listener beside the node’s own: the poll binds, moves or drops it and leaves every connection be, the handed-over ones included.”resyncisrebuild,rehandle,rebindor a new client; a[node.hysteria]edit sets bothrebuildand a new client. All of them are computed fromoldand the edit before anything is stored. - Store. The new
cfgreplaces the old one, and a new client replacesapi.collect_ipsis computed again from the client and the edited config; when collecting is now off, the addresses collected so far are cleared, so none of them is sent. - Apply. When the supervisor is up and
resyncis set,apply_staticruns onepoll_cycle(rebuild)at once.
That poll is a full cycle. A new client holds no ETags, so the panel answers in full and the node and users are read as the edited settings read them. With rebuild set, drop_all is true in reconcile, so the apply that commits is followed by close(Selector::All); otherwise drop_all and the spec comparison in reconcile decide from the fresh answer, as in the effect table. The poll also refreshes the rules and sends the report, as a timer poll does. It does not reset the poll interval.
For a node still in bootstrap nothing is polled: the edit is stored, or refused as in step 2, and the wait ends at once either way.
| Changed field | What happens | Takes effect |
|---|---|---|
route (the whole [node.route] table) |
poll_cycle(true): every session closed once the apply commits |
now |
controller.listen_ip, controller.cert, controller.disable_sniffing |
poll_cycle(true): every session closed once the apply commits |
now |
any [node.hysteria] field (on helium, congestion alone) |
new client, then poll_cycle(true): every session closed once the apply commits |
now |
api.enable_vless |
On newV2board with node_type V2ray or Vmess it changes the type the node is asked for, which is part of the identity (api::panel_node_type), so the runtime respawns the node. On any other newV2board node: new client, then poll_cycle(false), and the effect table decides from the fresh answer. Lowering reads only whether the node is Node::Vless or Node::Vmess, which the newV2board client decides by this key on a V2ray node. |
now |
enable_mtls |
new client, then poll_cycle(false): the effect table decides from the fresh answer. It is not part of the identity. |
now |
On helium, api.node_type, api.enable_vless or any [node.hysteria] key but congestion |
the reload is refused as a whole: apply_reload builds the client before it touches a running node, and helium::Client::new refuses the key |
never |
api.speed_limit, api.rule_list_path |
new client, then poll_cycle(false): the effect table decides from the fresh answer |
now |
controller.disable_vmess_clock_check, controller.enable_device_limit, ban_max_failures, ban_window_secs, ban_secs, carrier_max_failures, real_ip_header, real_ip_from |
poll_cycle(false); enable_device_limit also turns address collection on or off; only a WebSocket node reads the real-IP keys |
new connections, from the apply |
controller.handoff_dir, controller.handoff_group |
poll_cycle(false): the apply binds, moves or removes the handoff socket |
now; every connection is kept |
api.timeout, api.device_limit, an api.node_type change on newV2board that leaves the type the node is asked for unchanged (for example a case-only change, or v2ray to vmess with enable_vless on), a case-only panel_type change |
new client, then poll_cycle(false) |
now |
controller.update_periodic |
stored; the loop replaces the interval | the next poll, one new period later |
controller.disable_get_rule |
stored; try_bootstrap and poll_cycle read it before refresh_rules |
read by the next poll cycle |
controller.disable_upload_traffic |
stored; take_traffic reads it |
read by the next report |
controller.send_ip |
stored; nothing reads it | never |
The listener’s bind host and the inbound tag are built from controller.listen_ip (bind_host, inbound_tag in src/lower/inbound.rs), and so is the handoff socket’s name when the node listens on one address (handoff_file), so a listen_ip edit can move that socket as well.
An edit to the node’s identity, the panel node it serves, never reaches apply_static: the runtime removes the node and adds a new one. The identity tuple is on Runtime and config reload.
StaticUpdate::Globals
Section titled “StaticUpdate::Globals”The new Globals replaces the old one and rebuild_pending is set. When the supervisor is up, apply_static copies Cur::node and Cur::users and calls reconcile with them, without asking the panel. The resulting apply rebuilds what changed in the outbounds and DNS, and the pending drop closes every session. Every running node receives the update, so an [[outbound]] or [dns] edit closes every session on every node that is up; this is designed behaviour. A node still in bootstrap only stores the globals for its next attempt.
The runtime sends Globals to every node before it removes, reconfigures or adds any node. A reload that changes both the globals and a node’s [[node]] block in a way that needs a resync therefore reaches that node as two updates, each applied by its own reconcile.
The client-address task
Section titled “The client-address task”fn spawn_client_ips(self: Arc<Self>, shutdown: CancellationToken) -> JoinHandle<()>run calls it once, right after bootstrap, on every node. It gets the supervisor with .expect("the node is up"), which holds because bootstrap returned true, subscribes to the supervisor’s tracker, and then spawns a task that loops on an unbiased select! of the token and events.recv(). The supervisor sends FlowEvent::Opened when it registers a flow (Tracker::open), before any bytes move.
For each Opened event, the task takes the flow’s user label when the flow has a user (for a katana user, the uid in decimal, Uid::name). When collect_ips is set, the label parses as a uid and the flow has a source address, it inserts the uid and that address into client_ips, a set, so a user’s address is kept once per report. Closed events are ignored. When the receiver has fallen behind the channel, the task logs node <id>: missed <n> flow events at warn and goes on. The task stops when the token is cancelled or when recv returns RecvError::Closed. The second does not happen while the task runs: its Arc<NodeManager> keeps the supervisor handle, and with it the tracker’s broadcast sender, alive.
The task records nothing else. Before katana 6 it also recorded the flows opened on audit# outbounds as audit hits, for the illegal-access report that only SSPanel took; katana 6 removed both with SSPanel. Audit rules still route the flows they match to a blackhole, and no panel hears of them (see Destination audit).
Rules and reports
Section titled “Rules and reports”refresh_rules
Section titled “refresh_rules”api().node_rule() returning Ok(Some(rules)) goes to RuleManager::update, which replaces the rule set only when the ids or pattern strings differ, in order. Ok(None) keeps the current rules, and Err is logged as node <id>: node_rule: <error> at warn. Neither client makes a request for its rules, and both always return Ok(Some): the newV2board client builds the list from rule_list_path and the block routes cached by its last node_info, or inherited from the client it replaced, and the helium client from rule_list_path alone. The rules reach the supervisor only through the next lowering, which in poll_cycle follows at once.
report
Section titled “report”report is the node’s end of the usage cycle. It runs at the end of every poll cycle and once at exit. Without a supervisor it returns. Otherwise:
- A report. A
NodeReportwith a new randomid(uuid::Uuid::new_v4), the traffic fromtake_trafficand the addresses fromtake_client_ips. An empty report is not sent. - One request,
api().report, through the client current at that moment. - On failure it is logged as
node <id>: report <report id>: <error>atwarn.
take_traffic always calls supervisor.take_usage(), which returns every user’s wire bytes counted since the previous take, at most one UsageDelta per user. With controller.disable_upload_traffic set it returns no traffic: the usage is taken anyway, so nothing accumulates for the life of the process. Otherwise it sums the deltas by uid, drops the users whose upload and download are both 0, and converts each total to i64, saturating.
take_client_ips returns nothing unless collect_ips is set. Otherwise it takes the addresses the client-address task collected, adds the user and source of every session still open (supervisor.sessions()), so a connection that stays up is in every report while it lasts, and groups them by uid, each user’s addresses sorted.
The request each panel gets is on Panel clients.
take_usage visits one account per active user and lags by up to one sampler tick: a live session’s bytes are counted at each tick of DEFAULT_SAMPLE_INTERVAL (1 s), so what it moved since the last tick goes into a later take. A session that closes folds what it counted into its user’s account, and the next take includes it. A user removed mid-interval keeps their account, and the next take reports their final delta, so the take after a user-set change carries it. What is counted (wire bytes after the transport, QUIC UDP bytes for Hysteria 2) is on Per-user usage accounting. The counters behind it are on Traffic accounting and reporting.
The WireGuard shared-outbound warning
Section titled “The WireGuard shared-outbound warning”Because every node runs its own supervisor, a WireGuard [[outbound]] that several nodes route to becomes one tunnel per node, all with the same private key. A WireGuard peer keeps one session per key, so the tunnels keep taking it from one another and none of them works for long. katana does not share a tunnel between nodes; it logs a warning instead.
shared_wireguard in src/runtime.rs looks at every WireGuard outbound and lists the nodes that route to its tag, through route.default or any [[node.route.rule]]’s outbound. For every such outbound with more than one node, warn_shared_wireguard logs at warn, with the target katana::runtime:
wireguard outbound wg-out is routed to by 2 nodes (newv2board@https://panel.example.com#1/v2ray, helium@https://panel.example.com#2): each brings up its own tunnel with the same key, and the peer keeps only one of them at a timeEach node is shown by its log-safe identity (display_id): the lowercased panel type, the host, the node id and, on newV2board, the type the node is asked for, never api.key. The runtime runs the check at start-up, in --test (where the warning is printed before Configuration OK), and on every reload whose nodes all passed their checks. The configuration is still accepted. The remedy is one WireGuard outbound, with its own key, per node.
The exit steps of run:
servereturns when the token is cancelled.watch.await: the client-address task watches the same token and stops.- When a supervisor exists,
shutdown(Duration::ZERO). The supervisor stops every listener, cancels every balancer probe token (a katana spec has no balancers), closes its task tracker, gives no grace, cancels its root token (every session runs under a child of it,Sessions::open), waits for its tasks to be gone, clears its listeners, and then stops its sampler, which ticks once more. report. It runs after the shutdown because every session has ended by then and the sampler has published once more: this report carries what the node’s sessions counted up to shutdown, instead of leaving up to one poll of traffic untaken.
For a node that never came up there is no supervisor: step 3 is skipped and report returns at once. The runtime awaits each node’s task after cancelling it, both on process shutdown and when a reload removes the node, so these steps complete before the process exits or the reload moves on.
Invariants
Section titled “Invariants”| Invariant | Enforced by | Pinned by |
|---|---|---|
When an apply that changes the user set commits, unchanged users keep their principal and their sessions, and the principals of removed users are revoked under UserRemovalPolicy::Close. |
reconcile applies the new user set; admit keeps the principal of a user admitted by the same credential; revoked principals fall under the default removal policy. |
unchanged_user_survives_user_refresh (VMess over TCP), a_retired_user_stops_while_the_rest_keep_their_connections (Hysteria 2) in tests/unit/e2e.rs |
| Repeated user refreshes leave a live Hysteria 2 connection of a user who stays alive and relaying. | The bind is unchanged, so the plan keeps the listener; admit keeps the staying user’s principal. |
repeated_user_refreshes_never_disturb_a_live_connection |
| A routing edit drops every live connection on the node once its apply commits, even when it lowers to the same route table. | apply_static runs poll_cycle(true); reconcile checks drop_all before the spec comparison and closes after the commit. |
route_change_drops_connections |
An enable_vless edit on a newV2board V2ray node respawns the node as the other panel node it names, which then serves the other protocol. |
node_type_param is part of the identity, through api::panel_node_type. |
a_newv2board_type_edit_respawns_the_node in tests/unit/runtime.rs |
| A client-only edit takes effect without dropping connections. | apply_static builds a new client and runs poll_cycle(false); the rule change lowers to new audit routes, and the apply keeps sessions. |
a_client_edit_takes_effect_without_dropping_connections in tests/unit/runtime.rs |
An edit to enable_mtls alone gives the node a new panel client; an edit to nothing the client is built from keeps the one it has. |
apply_static compares panel_type, api, enable_mtls and hysteria. |
a_reload_of_enable_mtls_alone_rebuilds_the_client in tests/unit/manager/node.rs |
| A node whose bootstrap attempts fail keeps trying and comes up once the cause clears. | bootstrap retries with a capped, doubling wait. |
a_node_comes_up_once_the_panel_answers, a_node_whose_port_is_taken_comes_up_once_it_is_free |
| Each bootstrap attempt reads the node and users in full. | try_bootstrap calls forget_etags first. |
a_node_whose_port_is_taken_comes_up_once_it_is_free (the fake panel answers 304 to a repeated tag) |
| A node stops promptly while it retries its bootstrap. | bootstrap watches the token first in a biased select!, during each attempt and each wait. |
a_node_that_never_bootstraps_still_stops (within 2 s) |
Every exit path of run shuts a started supervisor down. |
No .await between Supervisor::start returning and the OnceLock being set; the exit steps test the OnceLock, not the bootstrap result. |
no dedicated test |
| Relayed bytes are reported under the authenticated uid. | take_traffic sums each UsageDelta under its Uid. |
vmess_traffic_is_metered_and_reported, proxy_outbound_relays_and_meters, a_hysteria_node_relays_and_meters |
Client addresses are reported only where enable_device_limit is on, and each is the session’s source: the connection’s peer, the client a PROXY protocol v2 header names (on the connection, or beside a handed-over one), or on a WebSocket node the client a trusted proxy’s real_ip_header names. |
collects_ips; the flow’s source. |
a_helium_node_without_enable_device_limit_reports_no_addresses |
Under enable_device_limit a user’s clients come from no more addresses than their device limit, and an address that keeps failing to authenticate is banned while others are served. |
lower_users keeps device_limit; policies sets ip_ban. |
a_users_clients_come_from_no_more_ips_than_their_device_limit, an_ip_failing_to_authenticate_is_banned_and_others_are_served |
| Lowering never runs on a runtime worker. | lower_off_runtime uses off_runtime. |
lowering_leaves_the_runtime_worker_free in tests/unit/manager/node.rs |
| An edit to the real-IP keys alone is applied by a poll at once, not at the next timer tick. | rehandle covers real_ip_header and real_ip_from. |
a_reload_of_the_real_ip_keys_alone_applies_at_once |
| An edit to the handoff keys alone binds the socket at once, and an edit that drops them removes it. | rebind; the plan binds and stops each bind on its own. |
a_reload_of_the_handoff_keys_alone_applies_at_once |
An unforced lowering equal to the running spec is Unchanged; a forced one never is. |
lower_off_runtime. |
a_spec_equal_to_the_running_one_is_unchanged_unless_forced |
| A panel speed limit paces the user’s traffic. | UserInfo::speed_limit into UserSpec::speed_limit, published by the supervisor at commit. |
a_users_speed_limit_paces_their_traffic (8 Mbps; 1.5 MB echoed each way, 3 MB through one shared bucket, takes at least 1.5 s) |
A flow to an audited domain is routed to its audit# blackhole, ahead of the node’s own routes. |
Audit routes first in the spec. | a_client_edit_takes_effect_without_dropping_connections (new flows to the listed name fail) |
| A panel-described Hysteria 2 node takes its port and obfuscation from the panel. | node_info asks the panel when hysteria.port == 0. |
a_panel_described_hysteria_node_serves_obfuscated_traffic |
| A helium node is never described locally, and a config that would describe its protocol does not build. | helium::Client::new refuses node_type and every [node.hysteria] key but congestion, so node_info always asks the panel. |
local_keys_the_panel_describes_are_refused in tests/unit/api/helium.rs |
| A change of a Hysteria 2 node’s masquerade, obfuscation or port, or of whether it relays UDP, closes every session; a new idle timeout or new rates do not, nor does a new AnyTLS padding scheme. | disruptive_part keeps all of the node but the padding scheme, the rates and the idle timeout. |
only_a_disruptive_change_drops_every_connection in tests/unit/manager/node.rs, on disruptive_part |
| A credential the panel never issued does not proxy. | The user set holds only the panel’s users. | a_hysteria_node_refuses_an_unknown_credential |
listen_ip = "0.0.0.0" serves both address families where :: takes IPv4. |
bind_host binds :: on a dual-stack host. |
a_node_on_0_0_0_0_serves_ipv4_and_ipv6_clients, a_hysteria_node_on_0_0_0_0_serves_ipv4_and_ipv6_clients |
disable_sniffing reaches the listener. |
Lowering sets the inbound’s sniff to !disable_sniffing; the field is a rebuild field. |
a_sniffed_host_reaches_a_domain_rule, disable_sniffing_stops_the_domain_rule_matching in tests/integration/sniff.rs |
| An identical rule list is not stored again. | RuleManager::update compares ids and pattern strings. |
update_skips_identical_ruleset in tests/unit/rule.rs |
| A WireGuard outbound that several nodes route to is reported, without the panel key. | shared_wireguard, display_id |
a_wireguard_outbound_several_nodes_route_to_is_reported, a_node_is_logged_by_its_panel_node_not_its_key in tests/unit/runtime.rs |
Cur::node is Some whenever poll_cycle runs. |
serve runs only after a successful bootstrap; apply_static polls only when the supervisor is set. |
no test; poll_cycle would panic the node task otherwise |
Failure paths and cancellation
Section titled “Failure paths and cancellation”Every node <id>: … line in this table is logged by src/manager/node.rs, so its tracing target is katana::manager::node.
| Failure | Where | Result |
|---|---|---|
| A bootstrap attempt fails (any row of the reasons table) | try_bootstrap |
node <id>: <reason>; retrying in <n>s at error; the next attempt after 1 s, doubling to 60 s and capped at the poll period; a Config update retries at once |
node_info fails in a poll, a UniProxy answer the client refuses included |
poll_cycle |
node <id>: node_info: <error> at warn, for a refusal node <id>: node_info: parse UniProxy config response: <reason>; Cur::node used |
user_list fails in a poll |
poll_cycle |
node <id>: user_list: <error> at warn; Cur::users used |
| The rules request fails | refresh_rules |
node <id>: node_rule: <error> at warn; the rules in force are kept |
| A config edit whose panel client does not build | apply_static |
node <id>: config edit refused, keeping the running one: <error> at error; nothing from the edit is stored |
| A report fails | report |
node <id>: report <report id>: <error> at warn |
| A spec does not lower in a poll | reconcile |
node <id>: cannot build the node, keeping the running one: <error> at error; the next cycle tries again |
| An apply is refused | reconcile |
node <id>: apply failed, keeping the running one: <error> at error; the next cycle tries again |
| The client-address task falls behind the flow-event channel | the client-address task | node <id>: missed <n> flow events at warn; the task goes on with the next event |
Cancellation
Section titled “Cancellation”Cancellation comes from the node’s CancellationToken, a child of the process root token (root.child_token() in runtime::spawn_built). The root is cancelled on SIGINT or SIGTERM; the node’s own token is cancelled when a reload removes the node. After cancelling, the runtime awaits the task.
- During bootstrap, both the attempt and the wait sit in a
biasedselect!with the token first, so a node that is cancelled while it is still coming up stops at once and drops any panel request or bind in flight. - In the steady state, the token is one branch of an unbiased
select!, so cancellation takes effect between iterations. Apoll_cycleor anapply_static(which may itself run a poll cycle) that is running when the token fires finishes first; its panel requests are bounded by the client timeout. When the token and a queued static update are both ready, tokio picks one at random, so that update may or may not be applied before the loop exits. - The client-address task watches the same token and ends on its own;
runawaits it before shutting the supervisor down.
Limits
Section titled “Limits”| Name | Value | Where |
|---|---|---|
update_periodic default |
60 s | default_update_periodic in src/config.rs |
Smallest update_periodic used (the interval’s period) |
1 s | NodeManager::poll_period (update_periodic.max(1)) |
| First bootstrap retry wait | 1 s | BOOTSTRAP_RETRY_MIN |
| Longest bootstrap retry wait | 60 s, or the poll period if shorter | BOOTSTRAP_RETRY_MAX; bootstrap caps each wait at poll_period() |
| Panel request timeout | api.timeout s, 5 s when 0 |
ApiConfig::timeout_secs in src/config.rs |
| Static-update channel | 16 updates | mpsc::channel(16) in runtime::spawn_built |
| Supervisor command channel | 16 commands | mpsc::channel(16) in SupervisorBuilder::start |
Sampler tick (the lag of take_usage) |
1 s; a delayed tick is not made up in a burst (MissedTickBehavior::Delay) |
DEFAULT_SAMPLE_INTERVAL and Sampler::run in supervisor/src/track/sampler.rs |
| Shutdown grace | 0 | run (shutdown(Duration::ZERO)) |
| Supervisors per node | 1 | NodeManager::supervisor (OnceLock) |
The manager’s own unit tests, in tests/unit/manager/node.rs (compiled into src/manager/node.rs), pin lower_off_runtime: lowering_leaves_the_runtime_worker_free (200 000 users lowered while a task on the one runtime worker keeps ticking), turning_the_vmess_clock_check_off_changes_the_spec and a_spec_equal_to_the_running_one_is_unchanged_unless_forced. only_a_disruptive_change_drops_every_connection pins disruptive_part: a new AnyTLS padding scheme, a new Hysteria 2 up_mbps and a new UDP idle timeout drop nothing, while turning UDP off, a new obfuscation password, a new port, a VMess node moved to WebSocket, a new masquerade or none, and new sss chains drop every connection. Three more pin apply_static on a node that is up: the helper running starts a real supervisor for a newV2board node on a free loopback port, whose panel cannot be reached, so a poll keeps the node and users it has and applies only what the config says. a_reload_of_the_real_ip_keys_alone_applies_at_once sets real_ip_header and real_ip_from on a WebSocket node, and the applied inbound has a real_ip once apply_static returns. a_reload_of_the_handoff_keys_alone_applies_at_once sets handoff_dir to a per-process temporary directory, and the applied inbound has a handoff socket whose file exists; an edit that clears it leaves the inbound without one, and after the supervisor’s shutdown the socket file is gone. a_reload_of_enable_mtls_alone_rebuilds_the_client edits disable_upload_traffic alone, and the node keeps the panel client it has (Arc::ptr_eq); it then turns enable_mtls off, and the node holds a new client and the new value. Beyond those, the manager is exercised end to end by tests/unit/e2e.rs, which src/main.rs compiles into the binary’s test harness as the e2e module, by the reload tests in tests/unit/runtime.rs, which src/runtime.rs compiles as its tests module, and by the rule tests in tests/unit/rule.rs, compiled into src/rule.rs.
The e2e tests run a hand-rolled fake newV2board panel on a loopback port. It serves /UniProxy/config and /UniProxy/user and records every /UniProxy/push body; reported_totals sums what was reported for a uid across them. fake_panel, fake_panel_dynamic (a user body the test can swap between phases) and fake_panel_with_config (a node body of the test’s choosing) are thin wrappers over fake_panel_quirky, which takes a Quirks value and also returns how many times the node config was asked for:
Quirks field |
Effect |
|---|---|
config_failures |
answer that many /UniProxy/config requests with 500 Internal Server Error before the first real answer, like a panel that is not up yet |
etags |
tag every answer with an ETag, and answer a request that sends the tag back with 304 Not Modified |
fake_helium serves Helium’s node API v2 for node 1 (/api/node/v2/1/config, /users and /report) from the config and users bodies the test passes, with ETags, records every report, and refuses a request without the bearer token. helium_users_body writes a users answer with the crate’s users::Users, held to no limits, and helium_node_cfg turns test_node_cfg into a helium node with no node_type. free_tcp_port picks a loopback port for a helium node to bind, since its port comes from the config body the test writes. limited_node runs a node under enable_device_limit whose one user has a given device limit and ban threshold; relayed_vmess_client connects through a relay that sends a PROXY protocol v2 header naming the client address of the test’s choosing. test_node_cfg builds a newV2board V2ray node with timeout = 5, listen_ip = "127.0.0.1" and update_periodic = 1. The e2e spawn_node helper builds a real PanelClient and NodeManager, spawns run with a channel of 16, and returns the sender so the channel stays open. a_node_whose_port_is_taken_comes_up_once_it_is_free holds its port on SPARE_LOOPBACK (127.0.0.2), an address no other test binds, so only the node it frees the port for can take it.
| Test | What it proves about the manager |
|---|---|
vmess_traffic_is_metered_and_reported |
bootstrap binds a VMess node, and report delivers the relayed bytes under uid 1001 |
unchanged_user_survives_user_refresh |
adding a user keeps user A’s connection; removing A drops it; A’s bytes from both phases are reported |
proxy_outbound_relays_and_meters |
a Globals outbound named by route.default carries the flow, and the bytes are still attributed |
route_change_drops_connections |
a StaticUpdate::Config whose route differs drops a live connection, although the lowered route table is the same |
a_users_speed_limit_paces_their_traffic |
with a panel speed_limit of 8 Mbps, 1.5 MB echoed each way (3 MB through one shared bucket with a 1 MB burst) takes at least 1.5 s |
a_node_comes_up_once_the_panel_answers |
with the first two config requests failing, bootstrap retries and the node binds and relays after the third |
a_node_whose_port_is_taken_comes_up_once_it_is_free |
a failed bind is retried, and against a panel that answers 304 each attempt still reads the node and users in full |
a_node_that_never_bootstraps_still_stops |
a node retrying against a panel that always fails stops within 2 seconds of cancellation |
a_node_on_0_0_0_0_serves_ipv4_and_ipv6_clients |
listen_ip = "0.0.0.0" relays for IPv4 and IPv6 clients; skipped where :: does not take IPv4 |
a_hysteria_node_relays_and_meters |
the local Hysteria 2 description binds, relays and reports |
a_hysteria_node_refuses_an_unknown_credential |
a credential the panel never issued does not authenticate |
a_hysteria_node_on_0_0_0_0_serves_ipv4_and_ipv6_clients |
the same as the stream test, over QUIC |
a_retired_user_stops_while_the_rest_keep_their_connections |
after the panel drops user B, B’s streams fail, while A’s existing QUIC connection stays alive and relays |
a_panel_described_hysteria_node_serves_obfuscated_traffic |
with hysteria.port == 0 the port and the Salamander key come from the panel |
repeated_user_refreshes_never_disturb_a_live_connection |
six polls that each change the user set leave one QUIC connection alive and relaying |
a_helium_node_without_enable_device_limit_reports_no_addresses |
without enable_device_limit, every report’s ips is empty |
an_sss_node_relays_through_its_chains_and_meters |
a helium node with no node_type comes up as the sss node its panel describes, on the panel’s port, relays through the panel’s chains and reports the bytes under uid 1001 |
a_users_clients_come_from_no_more_ips_than_their_device_limit |
with a device limit of 1, a second connection from the same address is served, one from a second address is refused, and the slot frees once the first device disconnects |
an_ip_failing_to_authenticate_is_banned_and_others_are_served |
after three failures an address is refused even with the right id, while another address is served |
a_panel_that_sets_rates_has_the_node_send_at_the_agreed_one, a_panel_silent_on_ignoring_client_bandwidth_keeps_the_node_on_auto, the_local_hysteria_block_overrides_the_panels_rates |
the panel’s Hysteria 2 rates, auto when the panel does not say, and [node.hysteria] overriding the panel |
The reload tests in tests/unit/runtime.rs hold a node the way runtime::run does (a Runtime with a root token and the node handles) and pass edited configs through apply_reload:
| Test | What it proves about the manager |
|---|---|
a_newv2board_node_is_also_the_type_it_asks_for |
which [[node]] edits change the identity (a respawn) and which reach the node as a Config update |
enable_mtls_is_on_unless_turned_off |
enable_mtls is true when the block does not name it, and turning it off does not change the identity, so it reaches the node as a Config update |
a_node_is_logged_by_its_panel_node_not_its_key |
display_id, the form the WireGuard warning and the reload log lines use: newv2board@<host>#<id>/v2ray on newV2board, helium@<host>#<id> on helium, never the key |
a_newv2board_type_edit_respawns_the_node |
turning enable_vless off on a newV2board V2ray node respawns it, and the new node serves VMess |
a_reload_with_a_node_that_does_not_build_changes_nothing |
an unknown node_type together with a route edit leaves the running node, its config and its live connection untouched |
an_sspanel_node_is_refused_at_test_and_at_start, a_reload_to_sspanel_changes_nothing |
a node whose panel_type is SSpanel is refused by name by --test and at start, where no node task is spawned for it; a reload that moves a running node to it is refused whole, and the node goes on serving as it was |
a_client_edit_takes_effect_without_dropping_connections |
a rule_list_path edit gets a new client whose rules refuse new flows to localhost at once, while an open connection keeps relaying |
a_wireguard_outbound_several_nodes_route_to_is_reported |
only a WireGuard outbound routed to by more than one node is reported, and the report does not contain the key |
The rule test in tests/unit/rule.rs, update_skips_identical_ruleset, pins the RuleManager::update the manager calls. The two sniffing tests in tests/integration/sniff.rs run the real katana binary against a fake panel with an Xray client in front; they skip themselves when Go or the Xray reference tree is not available (XRAY_BIN in tests/support/mod.rs).
Run them from the katana checkout:
cargo test --locked e2e::cargo test --locked manager::node::tests::cargo test --locked runtime::tests::cargo test --locked rule::tests::cargo test --locked --test integration sniff::No katana test covers a Globals update on a running node, a speed-limit change on a running node, a certificate replaced at the same path, a Hysteria 2 obfuscation change from the panel, a change of a Hysteria 2 node’s masquerade or UDP relay on a running node (only disruptive_part is pinned), or the per-uid merge in take_traffic on its own. A change to any of them needs a test in tests/unit/e2e.rs.