Skip to content

Runtime and config reload

Source files: 15 · checked against katana v6.1.0 · Etemenanki 46c12e4
  • katana/src/main.rs
  • katana/src/runtime.rs
  • katana/src/config.rs
  • katana/src/manager/mod.rs
  • katana/src/manager/node.rs
  • katana/src/api/mod.rs
  • katana/src/api/helium.rs
  • katana/src/api/hysteria.rs
  • katana/src/lower/mod.rs
  • katana/src/lower/route.rs
  • katana/tests/unit/runtime.rs
  • katana/tests/unit/manager/node.rs
  • katana/tests/integration.rs
  • katana/tests/support/mod.rs
  • Etemenanki/supervisor/src/supervisor.rs

src/runtime.rs is the root of a katana process, and src/config.rs defines the file it reads. The runtime loads the TOML config once, checks each [[node]] against what that node would run, and spawns one NodeManager task per node. Each node runs a supervisor of its own. The runtime then waits for a shutdown signal or a change reported by its config watcher. On a change it parses the file again, compares it with the running config, and checks every node the difference touches. If any check fails, it refuses the whole reload. An accepted reload is fanned out in a fixed order: the log filter, the process-wide outbounds and DNS for every node, removed nodes, and then one pass over the new [[node]] list that reconfigures kept nodes and spawns added ones.

This page is for contributors who change the config schema, the reload classification, the node identity rule or the StaticUpdate channel. It covers src/main.rs, src/config.rs, src/runtime.rs and the runtime’s side of src/manager/mod.rs. What a node does with an update once it has one is on Node manager. How a node’s config and its panel’s answer become a spec is on Lowering and Lowering inbounds and outbounds. The operator’s view of the same machinery is Hot reload.

Concern Owner Left to
Command line, --test, exit code src/main.rs → Args, main clap, for usage errors
The config schema and its parse src/config.rs → Config and its tables, load, parse_bytes toml and serde
What every node shares src/config.rs → Globals, Config::globals Each node, which lowers it into its own spec
Log subscriber and live level changes src/runtime.rs → init_tracing, LogReload tracing_subscriber::reload
Checking a node before it runs src/runtime.rs → build_node, check_node lower::test_spec and etemenanki_supervisor::check
One task per node, with its channel and token src/runtime.rs → spawn_node, spawn_built, NodeHandle NodeManager::run, for everything inside the node
The shared-WireGuard warning src/runtime.rs → shared_wireguard, warn_shared_wireguard Nobody: it only logs
Watching the config file src/runtime.rs → setup_watcher and the loop in run The notify crate
Classifying a reload and dispatching it src/runtime.rs → apply_reload, identity, display_id NodeManager::apply_static
The dry run src/runtime.rs → test_config The same checks a start runs
SIGINT and SIGTERM src/runtime.rs → wait_for_shutdown Each node’s own teardown

The runtime never binds a listener or applies a spec, and never reads a user list or a usage counter. The only spec it builds is the one check_node hands to etemenanki_supervisor::check. It reaches each node through two things only: a CancellationToken that stops it and an mpsc::Sender<StaticUpdate> that steers it.

There is no process-wide outbound pool. The runtime keeps the [[outbound]] and [dns] tables as Globals, and every node lowers them into its own spec. Each node’s supervisor therefore builds its own resolver, with its own cache, and its own instance of every outbound. etemenanki-app runs one supervisor for the whole process instead, and reloads it with a single apply; see etemenanki-app reload.

src/main.rs
/// XrayR-compatible proxy node agent on the Etemenanki kernel.
#[derive(Parser)]
#[command(version, about)]
struct Args {
/// Path to the TOML configuration file.
#[arg(short, long, default_value = "config.toml")]
config: PathBuf,
/// Validate the configuration and exit without binding any listener.
#[arg(long)]
test: bool,
}
#[tokio::main]
async fn main() -> ExitCode

main parses Args and always calls runtime::init_tracing(&args.config) first, so the dry run logs through the same subscriber as a real run. With --test it awaits runtime::test_config, prints Configuration OK to stdout on success or configuration error: <error> to stderr on failure, and returns. Otherwise it awaits runtime::run(args.config, reload). The Tokio runtime is the default multi-threaded one from #[tokio::main].

main.rs also declares the crate’s modules (api, blocking, config, lower, manager, rule, runtime) and, under #[cfg(test)], mounts tests/unit/e2e.rs as the module e2e. Under #[cfg(target_env = "musl")] it sets mimalloc::MiMalloc as the #[global_allocator]; see katana overview. The pinned binary prints:

katana --help
XrayR-compatible proxy node agent on the Etemenanki kernel
Usage: katana [OPTIONS]
Options:
-c, --config <CONFIG> Path to the TOML configuration file [default: config.toml]
--test Validate the configuration and exit without binding any listener
-h, --help Print help
-V, --version Print version
Exit code When
0 --test passed; run returned after a shutdown signal; clap printed --help or --version (katana 6.1.0)
1 --test failed; or, at start, the config did not load, has no [[node]], or no node passed its check
2 A usage error from clap, for example error: unexpected argument '--bogus' found

A node that cannot come up, for example because its panel is unreachable, does not change the exit code. It keeps retrying in its own task; see Node manager.

Paths are used as written. The config path, and every path inside the file (dns.ca_file, controller.cert.cert_file and key_file, route.geoip and geosite, api.rule_list_path), is opened relative to the working directory, not to the config file’s directory. controller.handoff_dir is the exception: lowering refuses it unless it is absolute.

src/config.rs is a set of serde structs. Every one of them derives Deserialize, Clone and PartialEq, and carries #[serde(deny_unknown_fields)], so a misspelt key anywhere in the file fails the parse instead of being ignored. PartialEq is what a reload compares with. The tree:

Config top level
├── log [log] LogConfig
├── dns [dns] DnsConfig
├── nodes [[node]] Vec<NodeConfig>
│ ├── panel_type
│ ├── enable_mtls
│ ├── api [node.api] ApiConfig
│ ├── controller [node.controller] ControllerConfig
│ │ └── cert [node.controller.cert] CertConfig
│ ├── route [node.route] RouteConfig
│ │ └── rules [[node.route.rule]] Vec<RuleConfig>
│ └── hysteria [node.hysteria] HysteriaConfig
│ └── masquerade [node.hysteria.masquerade] MasqueradeConfig
└── outbounds [[outbound]] Vec<OutboundConfig>

The tables below give each field’s Rust type, its default and the code that reads it. What each value means to a listener, an outbound or a route is on the page that owns that code; the user-facing reference is katana configuration.

Config also derives Default. Every field is #[serde(default)].

Field TOML Type Default Read by
log [log] LogConfig No level init_tracing, apply_reload
dns [dns] DnsConfig All unset Globals → lower::outbound::lower_dns
nodes [[node]] (rename = "node") Vec<NodeConfig> Empty The runtime. A start and --test need at least one
outbounds [[outbound]] (rename = "outbound") Vec<OutboundConfig> Empty Globals → lower::outbound::lower_outbounds
Field Type Default Meaning
log.level Option<String> Unset, read as "info" An EnvFilter directive string; see Logging
dns.backend Option<String> Unset, read as "system" "system", "udp", "tls" (DNS over TLS) or "https" (DNS over HTTPS)
dns.server Option<String> Unset The resolver’s IP address and port, such as 192.0.2.53:53: Backend::from_spec parses it as a socket address. Required by every backend but system, https included, “where taking the address from the URL would mean resolving the resolver”
dns.server_name Option<String> Unset tls only: the name the resolver’s certificate is verified against
dns.url Option<String> Unset https only: the resolver’s URL
dns.ca_file Option<String> Unset tls and https: the path of a PEM CA to verify the resolver against instead of the system roots. The spec carries the file’s bytes. The doc comment’s reason: “A private resolver is trusted this way without widening trust to all of Web PKI”

DnsConfig’s doc comment gives the reasons for the default: the host resolver is “the only one that honours /etc/hosts, nsswitch.conf and search domains”, the cache in front of it “is always on”, and “each node keeps a cache of its own”.

lower::outbound::lower_dns passes the four strings and the CA bytes to Backend::from_spec (protocols/src/dns/mod.rs), which refuses a table it cannot build. Its doc comment gives the rule: a backend that needs a server and has none “is an error rather than a quiet fall back to the host resolver: an operator who asked for a specific resolver must not silently get a different one”. The texts, captured from the pinned binary:

Cause Text
backend is none of the four dns: unknown backend "bogus" (expected "system", "udp", "tls" or "https")
udp, tls or https without server dns: the udp backend needs a server address, with tls or https in place of udp
server is not an IP address and port dns: invalid server address: invalid socket address syntax
tls without server_name dns: the tls backend needs a server name to verify against
https without url dns: the https backend needs the resolver's url

The resolver itself, including how an https URL is parsed, is on DNS resolver. How a spec’s DNS is built is on Name resolution and the DNS service.

NodeConfig has no Default. Every field has a serde default: enable_mtls through default_enable_mtls, which returns true, and the others through #[serde(default)].

Field Type Default Read by
panel_type String "" PanelClient::new, identity, api::panel_node_type. Compared case-insensitively: newv2board, v2board or helium. sspanel is refused by name, with panel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panels (the value as written); katana 6 removed the SSPanel client. The default is itself an unknown panel type
enable_mtls bool true (default_enable_mtls) Both panel clients, which pass it to build_http_client; NodeManager::apply_static, which builds a new client when it changes. katana presents a client certificate when a panel asks for one, unless the node sets enable_mtls = false, and does not follow redirects. Not part of the identity
api ApiConfig ApiConfig::default() The panel client, identity
controller ControllerConfig ControllerConfig::default() The node manager and inbound lowering
route RouteConfig Empty lower::route::lower_route, shared_wireguard
hysteria HysteriaConfig HysteriaConfig::default() api::hysteria::local (a locally described node, from NodeManager::node_info and lower::test_spec), the newV2board client, which keeps a copy to complete a panel’s Hysteria 2 node with (api::hysteria::uniproxy), Hysteria 2 lowering (credential and congestion), lower::test_spec (its congestion, on every node), and NodeManager::apply_static, which builds a new client when it changes. On a helium node only congestion may be set: helium::Client::new refuses any other key of the block

ApiConfig has a written-out Default that sets every field to its type’s zero value. Every field is #[serde(default)].

Field Type Default Read by
host String "" Every panel client, which trims trailing / (base_url, or helium’s node_url); identity, as written
node_id u32 0 Every panel request; identity; the node <node_id> prefix of node log lines and --test errors
key String "" Every panel client (newV2board’s token query parameter, helium’s Authorization: Bearer header); identity, which display_id renders without it
node_type String "" NodeType::parse, case-insensitive: v2ray, vmess and vless are the V2ray family, then trojan, shadowsocks, hysteria2, hysteria or hy2, anytls, socks or socks5, http, and sss. The newV2board client refuses anything else with unknown node_type "<value>", the value as written, and refuses sss too. The helium client refuses any non-empty value, since its panel names the protocol. Also lower::test_spec, NodeManager::node_info and newv2board::node_type_param
enable_vless bool false The newV2board client (the helium client refuses true), which reads a V2ray node’s answer as Node::Vless when it is set and as Node::Vmess when it is not, the variant inbound lowering (src/lower/inbound.rs → lower_stream_protocol) serves; newv2board::node_type_param, and through api::panel_node_type the identity
timeout u64 0 Seconds, through timeout_secs; the reqwest client’s request timeout
speed_limit f64 0.0 A speed limit in Mbps that, when positive, replaces every user’s limit from the panel; both clients write it into each UserInfo
device_limit i64 0 Nothing: the key is accepted and not read. A user’s device limit comes from the panel (see enable_device_limit)
rule_list_path String "" A local audit rule file, read by every client
src/config.rs
impl ApiConfig {
/// Timeout in seconds, defaulting to 5 when unset (0).
pub fn timeout_secs(&self) -> u64
}

katana 6 removed vless_flow and disable_custom_config, which only the SSPanel client read. ApiConfig denies unknown fields, so a file that still sets either fails the parse as an unknown key. How the clients use each field is on Panel clients.

Both have a written-out Default that matches their per-field serde defaults.

Field Type Default Read by
controller.listen_ip String "0.0.0.0" (default_listen_ip) Inbound lowering: the listener is built from it
controller.send_ip String "0.0.0.0" (default_listen_ip) Nothing: the key is accepted and not read
controller.update_periodic u64 60 (default_update_periodic) NodeManager::poll_period, as seconds, at least 1
controller.disable_upload_traffic bool false NodeManager::take_traffic
controller.disable_get_rule bool false NodeManager, which then skips the rule fetch
controller.disable_sniffing bool false Inbound lowering: the inbound’s sniff flag is its negation
controller.disable_vmess_clock_check bool false Inbound lowering: a VMess inbound’s clock_check is its negation
controller.enable_device_limit bool false lower_users, which keeps each user’s panel device limit only when it is on; lower::policies, which bans IPs only when it is on; collects_ips, for helium’s client addresses
controller.real_ip_header Option<String> Unset lower::inbound::real_ip, from lower_inbound and test_spec: the WebSocket upgrade header a trusted reverse proxy names the client in
controller.real_ip_from Vec<String> Empty lower::inbound::real_ip: the CIDRs of the proxies trusted to set real_ip_header; needed with it, and only with it
controller.ban_max_failures u32 30 (default_ban_max_failures) lower::policies: failed authentications from one IP that ban it (an IPv6 client’s whole /64 counts as one IP); 0 bans no one
controller.ban_window_secs u64 120 (default_ban_window_secs) lower::policies: the window those failures count within, in seconds
controller.ban_secs u64 300 (default_ban_secs) lower::policies: how long a ban lasts, in seconds
controller.carrier_max_failures u32 8 (default_carrier_max_failures) lower::policies: failed streams in a row that close a gRPC connection; 0 closes none
controller.handoff_dir Option<PathBuf> Unset lower::inbound::handoff, from lower_inbound and test_spec: the directory of each stream node’s handoff socket, <handoff_dir>/<port>.sock, or <handoff_dir>/<ip>-<port>.sock on one address; absolute, and short enough for the node’s socket name at port 65535 (96 bytes on every address)
controller.handoff_group Option<String> Unset lower::inbound::handoff: the group, by its name in /etc/group, that the sockets and a directory created for them are given; needs handoff_dir
controller.cert CertConfig CertConfig::default() Inbound lowering
cert.mode String "none" (default_cert_mode) Inbound lowering: "file" reads the two files below
cert.cert_file String "" Inbound lowering
cert.key_file String "" Inbound lowering
cert.reject_unknown_sni bool false Inbound lowering

The TLS rules are on Lowering inbounds and outbounds, and the policies on Lowering a node into a spec. The operator’s view of the device limit and the bans is Device limits and IP bans.

Field Type Default Meaning
route.default Option<CompactString> Unset, lowered as "direct" The outbound a flow that no rule matches leaves by
route.geoip Option<PathBuf> Unset Path of the GeoIP file. lower_route names it, stamped with the file at that path (RouteFile::stat), and the supervisor loads the sets the rules use
route.geosite Option<PathBuf> Unset Path of the GeoSite file, the same way
route.rules ([[node.route.rule]], rename = "rule") Vec<RuleConfig> Empty First-match rules
rule.outbound CompactString Required The outbound tag the rule sends to. A missing key is a parse error
rule.domain_suffix Vec<CompactString> Empty Lower-cased once by lower_route
rule.cidr Vec<String> Empty Parsed as IpCidr by lower_route
rule.port Vec<String> Empty Parsed by parse_port_match
rule.geosite Vec<CompactString> Empty GeoSite set names
rule.geoip Vec<CompactString> Empty GeoIP set names

How the table becomes a RouteSpec is on Lowering, and the matchers are on Route model.

Both carry #[serde(deny_unknown_fields, default)] at the container level and derive Default, so an absent key takes the value Default gives it.

Field Type Default Meaning
hysteria.port u16 0 Non-zero: the node is described locally (api::hysteria::local) and the panel is not asked for node info (NodeManager::node_info). Zero: the panel is asked, as for every other node type, and a node’s port is never 0: the contract’s port is a NonZeroU16, and the UniProxy client refuses a server_port outside 1 to 65535 with server_port <n> is not a port (1 to 65535). test_spec checks a zero port as 1
hysteria.credential String "", read as "uuid" "uuid": the credential is the user’s UUID. "user_pass": upstream’s user:pass, split on the first colon, with the user’s traffic label (the panel’s email, or the uid when that is empty) as the user name and the UUID as the password; a user whose label contains : is skipped. Anything else: unknown hysteria credential kind "token" (expected "uuid" or "user_pass")
hysteria.udp bool false Relay UDP as well as TCP
hysteria.udp_idle_timeout Option<u64> Unset, read as 60 when udp is on Seconds an association may stay quiet, 2 to 600, else udp_idle_timeout must be between 2 and 600 seconds. Set while udp is off: udp_idle_timeout is set but udp is not enabled
hysteria.obfs Option<String> Unset A locally described node only: "salamander", else unknown obfs "<obfs>" (expected "salamander")
hysteria.obfs_password Option<String> Unset A locally described node only: at least 4 bytes, else obfs_password must be at least 4 bytes for salamander. Set without obfs: obfs_password is set but obfs is not; did you mean obfs = "salamander"?
hysteria.up_mbps Option<u64> Unset The most the node sends one client at, in Mbit/s; overrides the panel’s up_mbps. 0 is no cap
hysteria.down_mbps Option<u64> Unset The most the node receives at, in Mbit/s, told to clients; overrides the panel’s down_mbps. 0 is no limit
hysteria.ignore_client_bandwidth Option<bool> Unset Overrides the panel’s. Unset here and at the panel, it is on: the node answers auto
hysteria.congestion Option<String> Unset, read as "cubic" The congestion control when no fixed rate is agreed: "cubic", "bbr" or "reno", else unknown hysteria congestion "<value>" (expected "cubic", "bbr" or "reno")
hysteria.masquerade MasqueradeConfig All unset What a client without a credential is answered with
masquerade.status Option<u16> Unset, read as 404 when another masquerade key is set The response status
masquerade.body Option<String> Unset, read as 404 page not found\n when another masquerade key is set The response body
masquerade.content_type Option<String> Unset, read as text/plain; charset=utf-8 when another masquerade key is set The response’s Content-Type

Every key of the block but credential and congestion reaches the lowering through the node, the contract’s Hysteria2, which src/api/hysteria.rs builds. obfs and obfs_password are read by local for a node described locally; a node described by its panel takes its obfuscation from the panel’s answer, held to the same rules by hysteria::obfs. The rates work the other way round: uniproxy takes the panel’s unless up_mbps, down_mbps or ignore_client_bandwidth here overrides them, and a locally described node has only these. On newV2board the settings its panel has no way to express, whether UDP is relayed and the masquerade, come from [node.hysteria] whether the node is described locally or by the panel, and so do the credential kind and the congestion control, which the lowering reads from the block itself. helium’s panel describes all of the block but congestion, so a helium node may set congestion alone; helium::Client::new refuses any other key. NodeConfig::hysteria’s doc comment: “A helium node’s panel describes all of it but congestion, and its client refuses the rest.” With all three masquerade keys unset, the supervisor’s default masquerade answers; with any of them set, katana fills in the others as above and judges the result with the contract’s validate() and the kernel’s Masquerade::new. The lowering and every refusal are on Lowering inbounds and outbounds.

One [[outbound]]. tag and protocol are required; every other field is #[serde(default)].

Field Type Default Used for
tag CompactString Required The name routes refer to
protocol String Required Compared case-insensitively: direct or freedom, socks or socks5, http, vmess, vless, shadowsocks or ss, wireguard or wg
server String "" Upstream host, an IP or a domain; the peer’s UDP endpoint for WireGuard. An IPv6 literal may be bracketed, and brackets hold nothing else
port u16 0 Upstream port
username, password Option<String> Unset SOCKS and HTTP accounts; the Shadowsocks password or PSK
uuid Option<String> Unset VMess and VLESS account id
security Option<String> Unset, read as "auto" VMess body cipher
method Option<String> Unset Shadowsocks cipher, which also picks legacy or 2022
global_padding bool false Accepted, no effect: the code comment gives the reason, the kernel’s VMess client always pads
address_family Option<String> Unset, read as auto Which address families the outbound’s destination DNS results may use: auto, ipv4_only, ipv6_only, prefer_ipv4, prefer_ipv6, and their aliases. For WireGuard it covers only destinations inside the tunnel
private_key, public_key, pre_shared_key Option<String> Unset WireGuard keys, base64 or hex
local_address Vec<String> Empty WireGuard tunnel addresses
mtu Option<usize> Unset, read as 1420 (DEFAULT_MTU) WireGuard tunnel MTU
keepalive Option<u16> Unset WireGuard persistent keepalive, seconds
reserved Option<Vec<u8>> Unset WireGuard reserved header bytes, exactly 3
endpoint_address_family Option<String> Unset, read as auto Which of a domain server’s addresses the WireGuard peer is dialled on, with the values of address_family

Four tags are built in and cannot be redefined: direct and freedom (freedom outbounds) and block and blackhole (blackholes). A tag that starts with audit# (rule::AUDIT_TAG_PREFIX) is reserved for audit rules. lower_outbounds refuses both kinds, and a repeated tag, with duplicate/reserved outbound tag <tag>. The comparison is exact, so Direct is an ordinary tag. Each protocol’s rules are on Lowering inbounds and outbounds.

src/config.rs
/// Load and parse a TOML config file.
pub fn load(path: impl AsRef<std::path::Path>) -> io::Result<Config>
/// Parse a TOML config from bytes.
pub fn parse_bytes(bytes: &[u8]) -> io::Result<Config>

load reads the whole file with std::fs::read and hands the bytes to parse_bytes. The errors:

Cause io::ErrorKind Text
The file cannot be read As the OS reports it The OS message, for example No such file or directory (os error 2)
The bytes are not UTF-8 InvalidData config not utf-8: <error>, for example config not utf-8: invalid utf-8 sequence of 1 bytes from index 0
TOML syntax, an unknown key, a missing required key, a wrong type InvalidData config parse error: <toml error>. Its first line names the position, for example config parse error: TOML parse error at line 9, column 1
src/config.rs
/// What every node lowers alongside its own settings.
#[derive(Clone, PartialEq, Default)]
pub struct Globals {
pub outbounds: Vec<OutboundConfig>,
pub dns: DnsConfig,
}
impl Config {
pub fn globals(&self) -> Globals
}

Globals exists only in memory: it is not Deserialize. Config::globals clones the two tables. The runtime wraps the result in an Arc: one Arc<Globals> is shared by every node at start, and a reload that changes either table builds a new one and sends it to every node.

A node keeps its copy as Mutex<Arc<Globals>> and lowers it into every spec it builds: lower::node_spec starts from shared_spec, which lowers globals.outbounds with lower_outbounds and globals.dns with lower_dns. Because every node has its own supervisor, every node builds its own resolver and its own instance of each outbound, including its own tunnel for each WireGuard outbound it routes to; see Shared WireGuard outbounds.

src/runtime.rs
type NodeId = (String, String, u32, String, String);
fn identity(cfg: &NodeConfig) -> NodeId
fn display_id(id: &NodeId) -> String

identity builds (panel_type lowercased, api.host, api.node_id, api.key, api::panel_node_type(cfg)). display_id renders one for logs without its key. Both are described under Node identity.

src/runtime.rs
/// A spawned node task plus the channels to steer and stop it.
struct NodeHandle {
id: NodeId,
cfg: NodeConfig,
task: JoinHandle<()>,
static_tx: mpsc::Sender<StaticUpdate>,
shutdown: CancellationToken,
}

run owns a Vec<NodeHandle>, one per spawned node. It is the runtime’s whole view of a node:

Field Use
id Matching against the identities of the next config
cfg The last [[node]] table the runtime sent this node, compared with != to decide whether a reload sends a StaticUpdate::Config
task Awaited when the node is removed and at shutdown
static_tx The sending half of the node’s update channel, capacity 16
shutdown A child of the root token; cancelling it stops this node only
src/manager/mod.rs
pub enum StaticUpdate {
/// This node's static `[[node]]` config changed (same panel identity). It
/// may touch `[node.api]` fields the panel client was built from; the node
/// rebuilds its client for those.
Config(Box<NodeConfig>),
/// The process-wide `[[outbound]]` entries or `[dns]` changed.
Globals(Arc<Globals>),
}

The enum’s doc comment sets the contract: it is “a configuration-file-driven update fanned out to a running node, distinct from the panel-driven poll cycle”, and “the runtime resolves node identity changes itself (respawn), so a node never receives a Config with a different panel identity”.

src/runtime.rs
/// A live-reloadable log-level setter, returned by [`init_tracing`].
pub type LogReload = Box<dyn Fn(&str) + Send + Sync>;
src/runtime.rs
pub async fn run(config_path: PathBuf, reload: LogReload) -> ExitCode
async fn spawn_node(
cfg: &NodeConfig,
globals: &Arc<Globals>,
root: &CancellationToken,
) -> Option<NodeHandle>
async fn build_node(cfg: &NodeConfig, globals: &Arc<Globals>) -> anyhow::Result<Arc<NodeManager>>
async fn check_node(cfg: &NodeConfig, globals: &Globals) -> anyhow::Result<()>
fn spawn_built(nm: Arc<NodeManager>, cfg: &NodeConfig, root: &CancellationToken) -> NodeHandle
async fn apply_reload(
cfg: &mut Config,
handles: &mut Vec<NodeHandle>,
new: Config,
reload: &LogReload,
root: &CancellationToken,
)
fn shared_wireguard(cfg: &Config) -> Vec<(&str, Vec<String>)>
fn warn_shared_wireguard(cfg: &Config)
pub async fn test_config(path: &Path) -> anyhow::Result<()>
pub fn init_tracing(config_path: &Path) -> LogReload
async fn wait_for_shutdown()
src/api/mod.rs
impl PanelClient {
pub fn new(cfg: &NodeConfig) -> anyhow::Result<Self>
}
pub fn panel_node_type(cfg: &NodeConfig) -> String
// src/api/newv2board.rs
pub fn node_type_param(api: &ApiConfig) -> String
// src/lower/mod.rs
pub fn test_spec(cfg: &NodeConfig, globals: &Globals) -> io::Result<Spec<Uid>>
// src/manager/node.rs
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>,
)
}
// etemenanki_supervisor (supervisor/src/supervisor.rs)
pub async fn check<U: UserId>(spec: &Spec<U>) -> Result<(), ApplyError>

NodeManager::new cannot fail and builds nothing: it stores the client, the config and the globals, and leaves the supervisor unset until the node first comes up. run is the node task’s body. It brings the node up, retrying until it is up or its token is cancelled. Then it starts the client-address task and serves (polls the panel and applies static updates) until the token is cancelled. After that it awaits the client-address task if the node came up, and shuts its supervisor down with Duration::ZERO if it has one (a bootstrap attempt cancelled after Supervisor::start has left one). All of this, and the rest of the node’s teardown, is on Node manager.

flowchart TB
  M["main"] --> I["init_tracing"]
  M --> R["run"]
  R -- "spawn_built" --> N1["node task 1"]
  R -- "spawn_built" --> N2["node task 2"]
  G["signal task"] -- "cancel" --> T["root token"]
  T -- "child token" --> N1
  T -- "child token" --> N2
  W["config watcher"] -- "change" --> L["select loop in run"]
  L -- "StaticUpdate, capacity 16" --> N1
  L -- "StaticUpdate, capacity 16" --> N2
  N1 --> S1["Supervisor of node 1"]
  N2 --> S2["Supervisor of node 2"]
Task or thread Started by Ends when
The select loop (the run future itself) main The root token is cancelled and every node task has been awaited
One node task, NodeManager::run spawn_built (tokio::spawn) Its token is cancelled and its teardown has finished. It never ends on its own
One client-address task per node, NodeManager::spawn_client_ips The node task, once the node is up The node’s token is cancelled, or the supervisor’s flow events close
The signal task run, after the watcher is set up The first SIGINT or SIGTERM; it then cancels the root token
The config watcher (notify) setup_watcher, called by run run returns and drops it
The supervisor’s own tasks Supervisor::start, inside each node That supervisor’s shutdown
  1. Tracing. main calls init_tracing, which reads [log].level from the file itself unless RUST_LOG holds a valid filter; see Logging.

  2. Load. run calls config::load(&config_path). This load is separate from the one init_tracing makes when RUST_LOG does not set the filter, which keeps only [log].level. On error it logs failed to load config: <error> and returns ExitCode::FAILURE.

  3. Require nodes. An empty cfg.nodes logs config defines no [[node]] entries and fails.

  4. Warn about shared WireGuard outbounds. warn_shared_wireguard(&cfg); see Shared WireGuard outbounds.

  5. Share the globals. Arc::new(cfg.globals()), and a new root CancellationToken.

  6. Spawn nodes, in file order. spawn_node awaits build_node for one node, then calls spawn_built, before it moves to the next node. A node that does not build logs node <node_id>: <error> and is skipped, so one bad [[node]] does not stop the others. A spawned node starts bringing itself up at once, in its own task, while the next node is checked.

  7. Require one node. If no handle resulted, run logs no nodes could be started and fails.

  8. Start the config watcher. run calls setup_watcher. If the watcher cannot be set up, it logs config watcher disabled (no live reload): <error> and continues without one. The returned RecommendedWatcher is held in _watcher until run returns; dropping it would end the watch.

  9. Arm signals. A detached task awaits wait_for_shutdown() and then cancels the root token.

  10. Loop. See The config watcher and the reload loop.

The pinned binary prints these start failures as follows (timestamps removed; every line has the level ERROR and the target katana::runtime):

ERROR katana::runtime: failed to load config: No such file or directory (os error 2)
ERROR katana::runtime: failed to load config: config not utf-8: invalid utf-8 sequence of 1 bytes from index 0
ERROR katana::runtime: config defines no [[node]] entries
ERROR katana::runtime: node 1: route references unknown outbound nope
ERROR katana::runtime: node 1: panel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panels
ERROR katana::runtime: no nodes could be started

build_node(cfg, globals) does everything about a node that can fail before its panel is asked, and binds nothing:

  1. PanelClient::new(cfg). panel_type is lowercased: newv2board or v2board builds PanelClient::NewV2board, and helium builds PanelClient::Helium. sspanel fails by name, with the value as written: panel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panels. Anything else fails with unknown panel_type "<value>", showing the lowercased value. The newV2board constructor parses api.node_type with NodeType::parse and fails with unknown node_type "<value>" on anything it does not know; it also refuses sss (newV2board: no UniProxy panel describes an sss node; sss is Helium's own protocol, served with panel_type = "Helium"). The helium constructor first runs refuse_local_protocol, which fails on the first of [node.api] node_type, enable_vless and every [node.hysteria] key but congestion that the table sets, for example [node.api] node_type is set, but a helium node's protocol is described by the panel; remove it (of [node.hysteria], only congestion is this host's to choose). Each then builds its reqwest::Client with build_http_client(api.timeout_secs(), cfg.enable_mtls). No request is sent.
  2. check_node(cfg, globals). One line: etemenanki_supervisor::check(&lower::test_spec(cfg, globals)?).await?.
  3. NodeManager::new(api, cfg.clone(), globals.clone()). It cannot fail.

lower::test_spec builds, in its doc comment’s words, “the spec --test and a reload check a node against before it runs”:

  • For every node it first calls inbound::real_ip(&cfg.controller)?, inbound::handoff(&cfg.controller)? and inbound::congestion(&cfg.hysteria)?, and drops the results: these keys are local, so half a real-IP setting, a typo, a handoff setting the relay could not use, or an unknown congestion control is refused here, before any panel names a WebSocket node, a port or (on helium) a Hysteria 2 node. handoff reads /etc/group when handoff_group is set.
  • For every node whose api.node_type is not Hysteria 2, a helium node with its empty node_type included, it is shared_spec(cfg, globals, &[]): the built-in and [[outbound]] outbounds (lower_outbounds), the resolver (lower_dns) and the node’s route (lower_route), with no audit rules, no inbound and no users.
  • For a node whose api.node_type parses as Hysteria 2, the doc comment gives the difference: “A hysteria node’s own settings are local on every panel but helium, so unlike every other node type’s they can be judged before the panel is asked.” test_spec describes the node with api::hysteria::local(&cfg.hysteria, port), the port 1 when [node.hysteria].port is 0, and lowers it with node_spec, an empty audit list and one placeholder user, “so the check builds the listener as a start would”. The placeholder is UserInfo { uid: 0, email: "placeholder", uuid: "placeholder", speed_limit: 0, device_limit: 0 }.

shared_spec lowers in a fixed order: the audit routes (none here), lower_outbounds, lower_dns, then lower_route; node_spec then lowers a Hysteria 2 node’s inbound with lower_inbound. The first lowering error is the one a check reports, so when several tables are wrong an [[outbound]] error is reported before a [dns] error, and both before a route syntax error or an inbound error. Only a spec that lowers reaches the supervisor.

Lowering a Hysteria 2 inbound goes through inbound::bind_host. For listen_ip = "0.0.0.0" that asks inbound::dual_stack(), which creates one IPv6 socket that is never bound, once per process (the answer is kept in a OnceLock). On a host whose IPv6 sockets take IPv6 alone it logs, at WARN, IPv6 sockets here take IPv6 alone (net.ipv6.bindv6only), so listen_ip 0.0.0.0 serves IPv4 only, so a check can print that line, under --test too. The bind rule itself is on Lowering inbounds and outbounds.

etemenanki_supervisor::check plans that spec from an empty running state in a throwaway actor and runs prepare without binding. It builds the resolver, every outbound, the route table with the geo sets its rules use, and every handler with its certificate, and then drops them. It binds no listener, dials nothing and does not open a Hysteria 2 endpoint. Semantic rules, such as a route naming an outbound that does not exist, belong to the supervisor; see Validation and apply errors and the dry-run section of Planning and applying a change.

What Checked for Refused by
panel_type, api.node_type Every node PanelClient::new
[node.api] node_type and enable_vless, and every [node.hysteria] key but congestion: none may be set helium nodes PanelClient::new → helium::Client::new
[node.hysteria] congestion: cubic, bbr or reno Every node lower::inbound::congestion
Every [[outbound]]; built-in, audit and repeated tags Every node lower_outbounds, then the supervisor’s build
[dns] Every node lower_dns (Backend::from_spec), then the supervisor’s build
controller.real_ip_header and controller.real_ip_from: both or neither, a header name, CIDRs Every node lower::inbound::real_ip
controller.handoff_dir and controller.handoff_group: an absolute directory short enough for the node’s socket, a group only with a directory, and a group /etc/group lists Every node lower::inbound::handoff
[node.route] rule syntax (cidr, port) Every node lower_route
Route tags that name no outbound; the geo files of the sets rules use Every node The supervisor’s validation and route build
A Hysteria 2 node’s inbound: [node.hysteria], controller.cert, and the certificate and key files Hysteria 2 nodes of newV2board api::hysteria::local, inbound lowering, then the supervisor’s handler build
Whether the panel answers, and whether its answer is a node katana can serve Nobody The panel client as it reads the answer, in the node’s bootstrap, which retries

Every node lowers and checks the same Globals, so an error in [[outbound]] or [dns] fails every node: --test reports it with the id of the first node whose panel client builds, and a start logs an error for every node and then no nodes could be started.

src/runtime.rs
fn spawn_built(nm: Arc<NodeManager>, cfg: &NodeConfig, root: &CancellationToken) -> NodeHandle {
let (static_tx, static_rx) = mpsc::channel(16);
let shutdown = root.child_token();
let task = tokio::spawn(nm.run(shutdown.clone(), static_rx));
NodeHandle {
id: identity(cfg),
cfg: cfg.clone(),
task,
static_tx,
shutdown,
}
}

spawn_built cannot fail and does not wait for the node to come up. A start reaches it through spawn_node; a reload calls it directly for the managers it built in its check stage.

since 4.1.0

shared_wireguard(cfg) goes through the WireGuard [[outbound]] tables. For each, it lists the nodes that route to its tag: a node whose route.default is the tag, or one of whose [[node.route.rule]] tables names it as outbound. It returns every such outbound with more than one node, each node rendered with display_id. warn_shared_wireguard logs one line per entry at WARN, with the target katana::runtime. The config is still accepted; the warning is all katana does about it. The reason, in short, is that every node runs its own supervisor, so each brings up its own tunnel with the same key, and a WireGuard peer keeps one session per key. The full explanation and the text of the line are on Node manager.

The runtime logs the warning at three points:

  • at start, after the [[node]] check and before any node is built;
  • by --test, before the per-node checks, so it is printed even when a later check fails;
  • by apply_reload, after every node of the new config has passed its check and before anything is applied.

run starts a config watcher with setup_watcher, which is built on the notify crate. When the watcher reports a change, the loop in run loads the file with config::load and passes the result to apply_reload.

  • A file that does not load logs config reload failed, keeping current: <error> at ERROR and changes nothing. The running cfg is kept, so the next reload compares against it, not against the file that failed.
  • Without a watcher (the config watcher disabled (no live reload) case at start), the loop waits on the root token alone.
  • The load and apply_reload run in the body of the loop’s select! branch, not as arms of the select!. A signal that arrives during a reload cancels the root token, and with it every node’s token, at once; the loop sees the cancellation when the reload returns.

apply_reload takes the running cfg and handles by mutable reference and applies a freshly parsed Config over them. Its doc comment: “A config any of whose nodes fails to check is rejected wholesale (nothing is applied).”

sequenceDiagram
  participant L as select loop
  participant R as apply_reload
  participant C as check_node
  participant K as kept node
  participant X as removed node
  participant N as added node
  L->>R: apply_reload(new)
  loop each new node table, in file order
    R->>C: check a changed or added node against the new globals
    C-->>R: ok or error
    Note over R: error means log and return, nothing applied
  end
  R->>R: warn_shared_wireguard(new)
  opt log level differs
    R->>R: reload(level)
  end
  opt outbounds or dns differ
    R->>K: StaticUpdate Globals
    R->>X: StaticUpdate Globals
  end
  R->>X: cancel token, await task
  loop each new node table, in file order
    alt identity matches a handle and the table differs
      R->>K: StaticUpdate Config
    else a node this reload adds
      R->>N: spawn_built with the manager built in the check
    end
  end
  R-->>L: cfg replaced by new
  1. Compare the globals. globals_changed is new.outbounds != cfg.outbounds || new.dns != cfg.dns. new_globals = Arc::new(new.globals()) is built either way, because added nodes are built against it.

  2. Check every node. The runtime walks the new [[node]] list once, in file order. For each table it computes the identity and looks for a running handle with that identity:

    Case What is built
    A running node, the same table (h.cfg == table), and globals_changed is false Nothing
    A running node, and the table differs or the globals changed PanelClient::new(table), built and dropped, then check_node(table, &new_globals)
    A node this reload adds build_node(table, &new_globals); the manager is kept in built

    The first failure logs reload: node <display_id>: <error>; keeping current config at ERROR and returns. Nothing is applied: not the log level, not the globals, no removal, and cfg is not replaced. The managers already built are dropped; none of them has bound anything. The code’s comment gives the reasons: an identity change is a remove plus an add, so a replacement that does not build would otherwise leave its node dark; and one node_type typo is a respawn on newV2board and a reconfigure on helium, and should be refused on both. A table moved to panel_type = "SSpanel" has another identity, so it is an addition whose build fails, and the whole reload is refused: reload: node sspanel@https://panel.example.com#1: panel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panels; keeping current config. A helium table that gains a refused key, node_type say, is refused here the same way, as a whole reload: reload: node helium@https://panel.example.com#1: [node.api] node_type is set, but a helium node's protocol is described by the panel; remove it (of [node.hysteria], only congestion is this host's to choose); keeping current config. When the globals changed, every running node is checked, including nodes whose own table did not change.

  3. Warn. warn_shared_wireguard(&new).

  4. Swap the log level. If new.log.level != cfg.log.level, the runtime calls reload(level), where an absent level becomes "info", and logs reload: log level → <level> at INFO.

  5. Send the globals. If globals_changed, StaticUpdate::Globals(new_globals.clone()) is sent to every handle in turn, including nodes that step 6 removes, and the runtime logs reload: outbound pool rebuilt at INFO.

  6. Remove nodes. The identities of the new config are collected into a HashSet<NodeId>. handles is drained. A handle whose identity is not in the set logs reload: removing node <display_id> at INFO, has its token cancelled and its JoinHandle awaited; the others are kept. Removals run one after another.

  7. Reconfigure and add, in one pass. The runtime walks the new [[node]] list again, in file order:

    • If a running handle has the identity and its cfg differs from the table, the runtime stores the table in the handle, sends StaticUpdate::Config(Box::new(table.clone())) and logs reload: reconfigured node <display_id> at INFO.
    • Otherwise, if built holds a manager for the identity, the runtime takes it out (swap_remove), logs reload: added node <display_id> at INFO and pushes spawn_built(nm, table, root) onto handles.
  8. Commit. *cfg = new. Only a reload that passed step 2 gets here.

Part of the config Compared by Sent as Effect on live connections
[log].level Option<String> != A call to LogReload None; no node is touched
[[outbound]] Vec<OutboundConfig> != StaticUpdate::Globals to every node Every session on every node that is up is closed once that node’s apply commits; see How a node applies a static update
[dns] DnsConfig != StaticUpdate::Globals to every node The same
A [[node]] table’s identity NodeId equality A removal, an addition, or both The removed node’s sessions end with its supervisor
The rest of a [[node]] table NodeConfig != against NodeHandle.cfg StaticUpdate::Config to that node See How a node applies a static update
The order of [[node]] tables Not compared Nothing None

The outbound list is compared as a whole Vec, so reordering [[outbound]] tables without changing any of them counts as a change and is sent to every node as Globals, like any other [[outbound]] edit. Moving a [[node]] table within the file does not, because nodes are matched by identity.

  • Checks come before any effect. Step 2 is the only step that can refuse, and it runs before anything is applied, sent or logged as applied.
  • Removals come before additions. Each removal awaits the node’s task, and the task ends only after the node’s supervisor has shut down. An added node is therefore spawned after every removed node’s supervisor has stopped, which is what lets an identity change, or a port that moves from a removed node to an added one, reuse the same port.
  • Removal waits for the node. A removal cancels the node’s token and awaits its task. A node in its serve loop sees the token in the loop’s select! once the poll_cycle or apply_static it is running returns. A node still coming up drops its current try_bootstrap attempt at once, because the bootstrap select! is biased toward the token. What the node does after that is on Node manager.
  • Updates are enqueued, not awaited. static_tx.send(…).await returns once the message is in the channel, and a send error is ignored. It waits only when 16 updates are already queued. A node takes messages from its channel in its serve loop’s select! and while it waits between bootstrap attempts, so messages queue while it runs a poll_cycle, an apply_static or a bootstrap attempt.
  • Globals first, then the table. A kept node whose table changed in the same save as the globals receives Globals in step 5 and Config in step 7, and each can end in closing every session.
  • Removed nodes are sent the globals too. Step 5 runs before step 6, so a node that step 6 removes is sent the new Globals as well. Whether it takes the message before it sees its cancellation depends on timing: the serve loop’s select! is not biased, and the bootstrap wait’s is biased toward the token.
  • Added nodes do not get a Globals message. They were built against new_globals and are spawned after step 5.

A [[node]] table in the new config is the same node as a running one exactly when their NodeId tuples are equal:

Position Source Compared as
0 panel_type to_ascii_lowercase(), so NewV2board equals newv2board. v2board and newv2board build the same client but are different identities
1 api.host The exact string: a trailing / makes another identity, although every client trims it
2 api.node_id u32
3 api.key The exact string
4 The panel node type, api::panel_node_type(cfg) For newv2board and v2board, newv2board::node_type_param(&cfg.api): "vless" for a node whose api.node_type is in the V2ray family (V2ray, Vmess or Vless, any case) and whose api.enable_vless is set, otherwise api.node_type lowercased. Empty for every other panel type

The identity says which panel node a table serves: which panel, which node on it, and with which credentials. NodeId’s doc comment explains the fifth element: newV2board finds a node by its id and the type it is asked for, “so one id asked as vless and as vmess is two nodes, each with its own users and traffic”. helium finds a node by its id alone, so the type is left out there.

What changes the identity, per panel:

Edit newV2board helium
panel_type other than its case, api.host, api.node_id, api.key New identity New identity
api.node_type to any other value than a case change New identity, except between the V2ray family’s values (V2ray, Vmess, Vless) while api.enable_vless is set, where the node is asked for as vless either way. Two spellings of one type, such as hy2 and hysteria2, or vmess and v2ray without enable_vless, are different identities Refused: the helium client refuses any node_type
api.node_type, case only Same node Refused, as above
api.enable_vless on a V2ray or Vmess node New identity Refused: the helium client refuses enable_vless = true
api.enable_vless on a Vless, Trojan, Shadowsocks, Hysteria 2, AnyTLS, Socks, Http or Sss node Same node: a Vless node is asked for as vless either way, and the flag means nothing to the others Refused, as above
enable_mtls, any other [node.api] field, and every other table Same node Same node

On helium a reload that sets api.node_type or api.enable_vless is refused before identities matter. A helium node’s identity is its panel, host, node id and key, and display_id shows it without a node type.

A new identity is a removal of the old node and an addition of a new one: a fresh NodeManager, with a new panel client and, once it comes up, a new supervisor.

display_id renders an identity for logs. With a non-empty node type it prints panel_type@host#node_id/node_type, for example newv2board@https://panel.example.com#1/v2ray; otherwise panel_type@host#node_id, for example helium@https://panel.example.com#1. It drops the fourth element, the key. The reload lines that name a node and the shared-WireGuard warning use display_id. Node-level log lines use the bare api.node_id instead: node 1: ….

A kept node whose table changed receives StaticUpdate::Config; every running node receives StaticUpdate::Globals when [[outbound]] or [dns] changed. NodeManager::apply_static decides what each one needs. Its doc comment states what it relies on: “The runtime resolves panel-identity changes (respawn) before dispatching, and has checked the edit builds.” In short:

  • Config. An edit to panel_type, to any [node.api] field, to enable_mtls or to [node.hysteria] builds a new PanelClient, which inherits the old one’s newV2board routes (inherit_routes). An edit to [node.route], controller.listen_ip, controller.cert, controller.disable_sniffing or [node.hysteria] is a rebuild (on helium, whose client refuses every other [node.hysteria] key, a congestion edit). A new client or a rebuild runs one panel poll at once, and a rebuild closes every session on the node once the apply commits. An edit to the clock check, the device-limit, ban and carrier keys or the real-IP keys (rehandle), or to the handoff keys (rebind), also runs one poll at once, and its apply keeps every session. The listener is built from controller.listen_ip. controller.update_periodic replaces the serve loop’s poll interval, and the other [node.controller] flags are stored and read where they are used. If the node’s own PanelClient::new fails, it logs node <node_id>: config edit refused, keeping the running one: <error> at ERROR and stores nothing; the runtime built a client from the same table in step 2, so this is a backstop.
  • Globals. The node stores the new Arc<Globals>, lowers itself again with the panel’s last answer and applies the spec with ApplyOptions { allow_disruptive: true }, without asking its panel. Once that apply commits, it closes every session on the node. An accepted edit to [[outbound]] or [dns] therefore closes every session on every node that is up, once that node’s apply commits, whether or not the node routes to the outbound that changed. This is designed: the module doc of src/manager/node.rs lists “a route, outbound or DNS edit, or the panel changing the node’s protocol or transport” as what “must drop every connection”, and says it “is closed out by the node after the apply commits”.
  • A node that has not come up yet only stores either update, and its first spec is lowered with what it stored. A Config also ends its wait between bootstrap attempts, so the next attempt starts at once with the new settings.

The per-field effect table, the poll and the reconcile that decide what to close are on Node manager.

src/runtime.rs
pub fn init_tracing(config_path: &Path) -> LogReload

init_tracing installs the global subscriber once, before --test or run:

  1. The initial filter is EnvFilter::try_from_default_env(), which reads RUST_LOG. If RUST_LOG is unset or holds an invalid directive, init_tracing loads the config file itself, separately from the load run or test_config makes afterwards, and keeps only [log].level from it, or "info" if the key is absent or the file does not load. That value goes through EnvFilter::new, which drops invalid directives with a line on stderr instead of failing, for example ignoring `=x`: invalid filter directive.
  2. The filter is wrapped in tracing_subscriber::reload::Layer::new, and the registry gets that layer and fmt::layer(), which writes to stdout.
  3. The returned LogReload parses a new level with EnvFilter::try_new. On success it calls handle.reload(filter) and ignores the result; on failure it logs invalid log level "<level>": <error> at ERROR, with the target katana::runtime, and keeps the current filter.

The level is an EnvFilter directive string, so it can name targets as well as levels (info,katana::runtime=debug). A bare word that is not a level, such as loud, is read as a target name, which enables only that target. A level applied by a reload replaces the whole filter, including one that came from RUST_LOG at start; removing [log].level in a reload sets info, not whatever RUST_LOG said.

src/runtime.rs
pub async fn test_config(path: &Path) -> anyhow::Result<()>

--test runs test_config, which runs the checks a start runs and stops short of spawning anything:

  1. config::load(path).
  2. At least one [[node]], or config defines no [[node]] entries.
  3. warn_shared_wireguard(&cfg).
  4. cfg.globals(), once. Then, for each node in file order: PanelClient::new(node_cfg), then check_node(node_cfg, &globals). The first error is returned as node <node_id>: <error>.

It binds nothing, starts no node task and sends no panel request. Captured from the pinned binary; each line is what --test prints to stderr, with exit code 1:

Check Example
The config file can be read configuration error: No such file or directory (os error 2)
UTF-8 configuration error: config not utf-8: invalid utf-8 sequence of 1 bytes from index 0
TOML syntax and unknown keys, such as the vless_flow and disable_custom_config that katana 6 removed (first line only) configuration error: config parse error: TOML parse error at line 9, column 1
At least one node configuration error: config defines no [[node]] entries
panel_type configuration error: node 1: unknown panel_type "xboard"
panel_type = "SSpanel" configuration error: node 1: panel_type "SSpanel" is not supported: katana serves the NewV2board and Helium panels
api.node_type configuration error: node 1: unknown node_type "V2rayy"
An sss node on newV2board configuration error: node 1: newV2board: no UniProxy panel describes an sss node; sss is Helium's own protocol, served with panel_type = "Helium"
A helium node’s local protocol keys configuration error: node 1: [node.api] node_type is set, but a helium node's protocol is described by the panel; remove it (of [node.hysteria], only congestion is this host's to choose), and the same with [node.api] enable_vless, [node.hysteria] up_mbps, [node.hysteria.masquerade] and the other refused keys
[node.hysteria] congestion, on every node configuration error: node 1: unknown hysteria congestion "vegas" (expected "cubic", "bbr" or "reno")
Built-in, audit and repeated tags configuration error: node 1: duplicate/reserved outbound tag direct, and the same with audit#1
Route tags configuration error: node 1: route references unknown outbound nope, for route.default or a rule’s outbound
Rule syntax configuration error: node 1: invalid cidr "10.0.0.0/33": invalid length for network: Network length 33 is too long for Ipv4 (maximum: 32)
Geo files of the sets rules use configuration error: node 1: building route failed: No such file or directory (os error 2)
DNS backend configuration error: node 1: dns: unknown backend "bogus" (expected "system", "udp", "tls" or "https")
DNS server address configuration error: node 1: dns: invalid server address: invalid socket address syntax
Hysteria 2 certificate mode configuration error: node 7: hysteria2 node requires cert.mode = "file"
Hysteria 2 certificate contents configuration error: node 7: building inbound Hysteria2_0.0.0.0_1 failed: hysteria2: the certificate file contains no certificates
Hysteria 2 settings configuration error: node 7: unknown hysteria credential kind "token" (expected "uuid" or "user_pass"), or configuration error: node 7: obfs_password is set but obfs is not; did you mean obfs = "salamander"?

A half or malformed real-IP pair fails every node type the same way, for example configuration error: node 1: real_ip_header needs real_ip_from: the proxies trusted to set it or configuration error: node 1: real_ip_from is set without real_ip_header; the texts are listed on Lowering inbounds and outbounds. So does a handoff setting the relay could not use, for example configuration error: node 1: handoff_group is set without handoff_dir, configuration error: node 1: handoff_dir "run/katana/handoff" must be an absolute path or configuration error: node 1: handoff_group "no-such-group-here" is not a group in /etc/group (The handoff socket). The group is looked up in the /etc/group of the host that runs --test, so check a file on the host it is for.

The inbound tag in the certificate line comes from inbound::inbound_tag, <Type>_<listen_ip>_<port>: listen_ip as configured, not the host bind_host binds, and the placeholder port 1 that test_spec substitutes for [node.hysteria].port = 0. A geo file that no rule uses is not opened, so a wrong route.geoip path passes until a rule names a GeoIP set.

--test is stricter than a start: run logs a node that does not build, skips it and serves the others, while --test fails on the first such node. It runs the same check a reload runs for a changed or added node. Because init_tracing runs first, a [log].level with an invalid directive does not fail --test; the dropped directive is reported on stderr and the run still prints Configuration OK. The shared-WireGuard warning goes to stdout, before Configuration OK or the error.

wait_for_shutdown returns on the first SIGINT (tokio::signal::ctrl_c) or, on Unix, SIGTERM (signal(SignalKind::terminate())). If the SIGTERM handler cannot be installed, it waits for SIGINT alone; on other platforms it waits for Ctrl-C only.

When it returns, the signal task cancels the root token. Every node’s token is a child_token() of the root, so the cancellation reaches every node at once. The loop breaks, logs shutting down at INFO, cancels the root again (a no-op) and awaits every JoinHandle in handles, in order. Each node leaves its bootstrap or serve loop and, if it came up, awaits its client-address task. If it has a supervisor, it calls Supervisor::shutdown(Duration::ZERO): with zero grace, the supervisor stops accepting, closes whatever is left and waits for it to be gone (supervisor overview). Then the node reports its traffic one last time (Traffic accounting). run then returns ExitCode::SUCCESS.

  • There is no SIGHUP handler. A reload is started only by the watcher, and SIGHUP keeps its default action, which ends the process without this sequence.
  • The signal task is spawned at the end of startup. Until it first runs, SIGINT and SIGTERM also have their default action.
  • Once registered, Tokio’s handlers stay installed, so a second SIGINT or SIGTERM during shutdown does not end the process early.
Invariant Enforced by Pinned by
A reload with a node that does not check changes nothing apply_reload checks every changed and added node, and builds every added one, before its first side effect a_reload_with_a_node_that_does_not_build_changes_nothing reloads a node_type typo (V2rayy) together with a route edit and asserts that the node was not replaced (same_channel), that neither the handle’s cfg nor the runtime’s cfg changed, and that an open VMess connection still relays
A helium node whose table would describe its protocol is refused at start, by --test and on reload helium::Client::new → refuse_local_protocol, which build_node, test_config and apply_reload all reach through PanelClient::new local_keys_the_panel_describes_are_refused in tests/unit/api/helium.rs, for each of the thirteen keys, through PanelClient::new too
A node that names SSPanel is refused by name at start and by --test, and a reload that moves a running node to SSPanel changes nothing PanelClient::new, which build_node, test_config and step 2 of apply_reload all run an_sspanel_node_is_refused_at_test_and_at_start asserts the refusal from test_config and build_node, and that spawn_node returns no handle; a_reload_to_sspanel_changes_nothing asserts that the running node keeps its handle and channel, that the runtime’s cfg did not change, and that a new VMess connection still relays
A node never receives a Config for another panel node identity covers the panel, host, node id, key and panel node type; a mismatch is a removal and an addition a_newv2board_node_is_also_the_type_it_asks_for and enable_mtls_is_on_unless_turned_off pin which edits change the identity; a_newv2board_type_edit_respawns_the_node turns VLESS off on a newV2board V2ray node and asserts a new channel and that the node no longer serves VLESS
An edit to a field the panel client was built from takes effect in place apply_static builds a new PanelClient when panel_type, [node.api], enable_mtls or [node.hysteria] changes, then polls once a_client_edit_takes_effect_without_dropping_connections sets api.rule_list_path and asserts that new flows to the named target are refused while an open connection keeps relaying; a_reload_of_enable_mtls_alone_rebuilds_the_client in tests/unit/manager/node.rs asserts a new client after an enable_mtls edit, and the same client after an edit to controller.disable_upload_traffic
A route edit closes every session on the node once its apply commits apply_static → poll_cycle(true) → reconcile → close(Selector::All) route_change_drops_connections in tests/unit/e2e.rs sends a StaticUpdate::Config with a new [node.route] over a capacity-16 channel and asserts the open VMess connection ends
An accepted [[outbound]] or [dns] edit closes every session on every node that is up, once that node’s apply commits apply_reload sends Globals to every handle; apply_static sets rebuild_pending and reconciles No test
The runtime renders a node identity without its key display_id drops the fourth element; the reload lines that name a node and the shared-WireGuard warning use it a_node_is_logged_by_its_panel_node_not_its_key pins both renderings; a_wireguard_outbound_several_nodes_route_to_is_reported asserts that no node in the result contains the key
Only a WireGuard outbound that several nodes route to is reported shared_wireguard counts the nodes that route to each WireGuard outbound and keeps those with more than one a_wireguard_outbound_several_nodes_route_to_is_reported: of uk (wireguard, two nodes, one by default and one by rule), it (wg, one node) and relay (SOCKS, two nodes), only uk is reported, with nodes #1 and #2
Built-in and audit tags cannot be redefined lower_outbounds seeds the built-ins and refuses a tag that exists or starts with audit# an_audit_tag_is_reserved in tests/unit/lower/spec.rs; the built-in tags are reproducible with katana --test
Removed nodes are gone before added nodes start Step 6 awaits every removed task before step 7 spawns No test; the order of statements in apply_reload
A node that cannot come up still stops when cancelled NodeManager::bootstrap watches the token in a biased select!, also during an attempt a_node_that_never_bootstraps_still_stops in tests/unit/e2e.rs
One bad [[node]] at start does not stop the others spawn_node logs and returns None; run requires one handle, not all No test
Failure Where Result
The config does not load run failed to load config: <error> at ERROR, exit 1
No [[node]] run config defines no [[node]] entries, exit 1
A node does not build spawn_node node <node_id>: <error>; that node is skipped and the others are started
No node builds run no nodes could be started, exit 1
The watcher cannot be set up run config watcher disabled (no live reload): <error>; the process runs without reloads
A node’s panel is unreachable or its port is taken The node task Retried with backoff inside the node; see Node manager
--test finds an error test_config configuration error: <error> on stderr, exit 1
Failure Where Result
The file does not load The select loop in run config reload failed, keeping current: <error>; nothing applied
A changed or added node does not check apply_reload, step 2 reload: node <display_id>: <error>; keeping current config; nothing applied, cfg not replaced
The new log level is invalid The LogReload closure invalid log level "<level>": <error>; the old filter is kept
A send to a node’s channel fails apply_reload, steps 5 and 7 Ignored
  • The root token is created by run; each node gets root.child_token(). Cancelling the root cancels every node; cancelling a node’s token, as a removal does, stops that node only.
  • A node spawned while the root is already cancelled, for example by a reload that was running when the signal came, gets a child token that is cancelled from the start, and stops at once.
  • apply_reload itself is not cancellable: it runs to its end inside the select branch, and the loop checks the token afterwards.
  • test_config has no token; it ends when its last check ends.
Value Where Meaning
16 mpsc::channel(16) in spawn_built Queued StaticUpdates per node before send waits
"info" init_tracing, apply_reload Log level when [log].level is absent
5 s ApiConfig::timeout_secs Panel request timeout when api.timeout is 0
60 s, at least 1 s default_update_periodic, NodeManager::poll_period Poll period
1 s to 60 s BOOTSTRAP_RETRY_MIN, BOOTSTRAP_RETRY_MAX in src/manager/node.rs Wait between bootstrap attempts, doubling; the poll period caps it when shorter
Duration::ZERO NodeManager::run Grace of each node’s supervisor shutdown
"0.0.0.0" default_listen_ip Default listen_ip and send_ip
"none" default_cert_mode Default cert.mode
1 lower::test_spec Port a Hysteria 2 node is checked with when [node.hysteria].port is 0
60 s, 2 to 600 s udp in src/api/hysteria.rs hysteria.udp_idle_timeout when udp is on and it is unset, and its accepted range (a helium node’s idle timeout, from its panel, is held to the same range)
u32 ApiConfig::node_id Range of a node id

src/runtime.rs mounts tests/unit/runtime.rs as its test module (#[path = "../tests/unit/runtime.rs"] mod tests;), so the tests reach the private functions through use super::*.

Identity, without I/O. The helper node(panel_type, node_type) builds a table with host https://panel.example, node id 3 and key SECRET; same_node(base, edit) compares identities before and after an edit.

  • a_newv2board_node_is_also_the_type_it_asks_for: on newV2board, api.enable_vless on a V2ray node and api.node_type change the identity; api.speed_limit, api.rule_list_path, api.timeout and a case-only node_type edit do not; on a Trojan node api.enable_vless does not.
  • a_node_is_logged_by_its_panel_node_not_its_key: display_id renders newv2board@https://panel.example#3/v2ray and helium@https://panel.example#3.

The schema, without I/O. the_real_ip_keys_parse_and_a_typo_in_them_is_refused parses a node whose inline controller table sets real_ip_header = "X-Real-IP" and real_ip_from = ["127.0.0.1/32", "::1/128"] with config::parse_bytes, and checks that a misspelt set_real_ip_from fails the parse as an unknown key instead of leaving the node reading no header. the_handoff_keys_parse_and_a_typo_in_them_is_refused does the same for handoff_dir and handoff_group, with handoff_directory as the misspelling, which would otherwise leave the node without its socket. enable_mtls_is_on_unless_turned_off parses one node without the key and one with enable_mtls = false, checks that the first reads true and the second false, and that turning it off keeps the identity.

Reloads against a live node. The Runtime harness holds cfg, the root token and handles the way run does. Runtime::start spawns one node with the real spawn_node (so check_node runs), Runtime::reload calls apply_reload with a no-op LogReload, and Runtime::stop cancels the root and awaits every task. The nodes serve against fake_panel from tests/unit/e2e.rs on a port from free_port. A test tells a respawn from an in-place edit by comparing the handle’s static_tx with same_channel.

  • a_newv2board_type_edit_respawns_the_node, a_reload_with_a_node_that_does_not_build_changes_nothing, a_reload_to_sspanel_changes_nothing and a_client_edit_takes_effect_without_dropping_connections, described under Invariants. The last writes its rule file through TmpFile, which removes the file when dropped.
  • an_sspanel_node_is_refused_at_test_and_at_start runs no Runtime: it writes an SSPanel node to a file through TmpFile, runs test_config on it, then build_node and the runtime’s spawn_node on the loaded config, and expects panel_type "SSpanel" is not supported from each and no handle from spawn_node.
  • a_wireguard_outbound_several_nodes_route_to_is_reported parses a config with config::parse_bytes and calls shared_wireguard directly; it does not check that the warning is logged.

The node side, in tests/unit/e2e.rs. Its helper spawn_node(cfg, globals) mirrors the runtime’s without the check: PanelClient::new, NodeManager::new, mpsc::channel(16) and tokio::spawn(nm.run(…)). test_node_cfg is a newV2board V2ray node with api.timeout = 5, listen_ip = "127.0.0.1" and update_periodic = 1.

  • route_change_drops_connections sends a StaticUpdate::Config with route.default = "direct" and asserts that a live VMess connection ends within 10 seconds.
  • a_node_comes_up_once_the_panel_answers, a_node_whose_port_is_taken_comes_up_once_it_is_free and a_node_that_never_bootstraps_still_stops (the task must end within 2 seconds of the cancel) cover the node lifecycle the runtime relies on.

Reserved tags, in tests/unit/lower/spec.rs: an_audit_tag_is_reserved lowers a node with an [[outbound]] tagged audit#1 and expects an error containing reserved.

The whole process, in tests/integration.rs, which mounts tests/support/mod.rs and the three files under tests/integration/. spawn_katana in tests/support/mod.rs runs the real binary (CARGO_BIN_EXE_katana) as -c katana.toml in a per-test directory, with stdout and stderr discarded. Every such test that runs its peer therefore goes through main, init_tracing, run, spawn_node with check_node, and setup_watcher on a bare relative path. The tests are vmess_tcp_plain, vmess_ws_plain, vmess_grpc_plain, vmess_tcp_tls, vless_ws_tls, vless_grpc_tls, trojan_tcp_tls and the three _mux variants in xray_interop.rs; a_sniffed_host_reaches_a_domain_rule and disable_sniffing_stops_the_domain_rule_matching in sniff.rs; and a_real_client_proxies_through_a_katana_hysteria_node in hysteria_interop.rs. They build their peer (Xray or the Hysteria client) with go, and print a SKIP: line and pass, before spawn_katana runs, when the toolchain or the peer’s source is missing or the build fails. None of them edits katana.toml.

Not covered by a test: a Globals update, what --test prints (test_config itself is run only by an_sspanel_node_is_refused_at_test_and_at_start), a reload started by the watcher, signal handling, a start where one node fails and another starts, and the emission of the shared-WireGuard warning. katana --test -c <file> reproduces every row of the dry-run table by hand. How the suites are organised and run is on Testing.

When you change apply_reload, the step order above is the contract to keep, and tests/unit/runtime.rs with its Runtime harness is where a test for a new reload path belongs.