diff --git a/src/workerd/server/AGENTS.md b/src/workerd/server/AGENTS.md index bacc17dd926..90f06fc2981 100644 --- a/src/workerd/server/AGENTS.md +++ b/src/workerd/server/AGENTS.md @@ -54,7 +54,7 @@ Bazel labels: `//src/workerd/server:workerd`, `//src/workerd/server:workerd-cli` | `lib.rs` | Crate root: `main()`, the commands, the server's `Watch` future for `--watch` | | `args.rs` | clap definitions | | `help.rs` | The help pages, written by hand; `args-test.rs` checks them against the parser | -| `config.rs` | Config sources (schema file, compiled binary, embedded) and the synthesized Python config; for `serve`, in one pass (`with_cluster`), `--cluster-addr` joining a config without `cluster` to one, refused for a compiled binary's config and for one without a writable `do-storage` disk, and the cluster key and bucket taken from `WORKERD_CLUSTER_KEY` or `WORKERD_CLUSTER_KEY_FILE` and `WORKERD_CLUSTER_BUCKET` over the config's, an error if set nowhere | +| `config.rs` | Config sources (schema file, compiled binary, embedded) and the synthesized Python config; for `serve`, in one pass (`with_cluster`), `--cluster-addr` joining a config without `cluster` to one, refused for a compiled binary's config and for one without a writable `do-storage` disk, and the cluster key and bucket taken from `WORKERD_CLUSTER_KEY` or `WORKERD_CLUSTER_KEY_FILE` and `WORKERD_CLUSTER_BUCKET` over the config's, an error if set nowhere, and `stopTimeoutMs` taken from `WORKERD_CLUSTER_STOP_TIMEOUT_MS` over the config's; and `shutdownDelayMs` taken from `WORKERD_SHUTDOWN_DELAY_MS` over the config's (`with_shutdown_delay_environment`) | | `deploy.rs` | Cluster mode: `workerd deploy`, a wrangler project (`wrangler.rs`) or Cap'n Proto config checked as a deployment, then published to the bucket `--bucket` names (`cluster::deploy`), with the instances' bucket client and environment fallbacks; each instance skips it if it does not compose with its own config | | `deployments.rs` | Cluster mode: before `serve` starts the server, merges deployments from the bucket (`cluster::deploy`) into the config (`cluster::compose`), skips those that do not compose, and tells the server which services came from each deployment | | `process.rs` | Executable discovery, the compiled-binary format, `Process` (the files to watch, re-exec) | @@ -70,7 +70,7 @@ Bazel labels: `//src/workerd/server:workerd`, `//src/workerd/server:workerd-cli` | `lib.rs` | Crate root: `Error` / `Result` | | `bridge.rs` | The cxx bridge (`workerd::server`) to `factory/worker-factory.h` and `factory/bootstrap.h`. `extern "C++"`: the factory (compile, start request, bench, actors and storage, RPC, tokens, inspector, `factory_spawn`), the bootstrap, the process's logging and its exit; `extern "Rust"`: the channel objects, the channel factory, the pending command. Ownership rules in its `//!` | | `entry.rs` | `serve` / `test` / `bench`: the process's schedule (`with_process_context`, the `kj_rs_tokio::Runtime`, `bootstrap`, `block_on`, exit), `server_serve` / `server_test` / `server_bench`, the `Watch` future the command line supplies, printing config errors and the exit status they make, SIGTERM drain, `--watch` reload, shutdown order (settle tasks, drop the factory and with it V8 and the perfetto session, then the Runtime) | -| `run.rs` | `run()` / `test()` / `bench()`: bind sockets, start the inspector (before any isolate exists), build the graph, start the listeners (not for a config the `Reporter` refuses), drain, control-fd events, the check that every `--directory-path` / `--external-addr` override named a service | +| `run.rs` | `run()` / `test()` / `bench()`: bind sockets, start the inspector (before any isolate exists), build the graph, start the listeners (not for a config the `Reporter` refuses), drain (after the config's `shutdownDelayMs`, which a second drain signal cuts short; at once for a signal that came while it started), control-fd events, the check that every `--directory-path` / `--external-addr` override named a service | | `bench.rs` | `workerd bench`'s options and report (`io/bench.capnp`): a group for each `bench()` handler `run::bench` runs (through the factory's `worker_bench`), progress logged as `workerd test` logs it, the environment, and the report as a table or as JSON | | `config.rs` | `Server`: the service graph from the config in three passes (actor configs, construction, link); `Factory`, the Rust owner of the C++ `WorkerFactory`; `Reporter`, which attributes a deployment's config errors to it; resolves channel tokens and debug-port requests | | `channels.rs` | The handles C++ holds and the runtime reaches into the server through: `SubrequestChannel` (an `Rc`), `ActorClassChannel` (an `Rc`), `ChannelFactory` (a worker's `LinkedChannels`), `WorkerStub`, and the `Weak` back-pointers (`ServerHandle`, `ActorNamespaceHandle`, `ActorHooks`). Single-threaded | diff --git a/src/workerd/server/cli/config-test.rs b/src/workerd/server/cli/config-test.rs index f27b2e21a0d..af1b43c4ac3 100644 --- a/src/workerd/server/cli/config-test.rs +++ b/src/workerd/server/cli/config-test.rs @@ -452,6 +452,126 @@ fn a_config_joins_and_takes_the_environment_in_one_pass() { assert!(error.starts_with("cluster.key is not set."), "{error}"); } +/// A config with a cluster with `KEY` and a bucket, and with `stopTimeoutMs` set to `timeout`, if +/// any. +fn stop_timeout_config(timeout: Option) -> Config { + let mut message = capnp::message::Builder::new_default(); + let mut root = message.init_root::(); + root.reborrow().init_services(1).get(0).set_name("main"); + let mut cluster = root.init_cluster(); + cluster.set_key(KEY); + cluster.set_bucket("s3://bucket/prefix"); + cluster.set_address("127.0.0.1:0"); + if let Some(timeout) = timeout { + cluster.set_stop_timeout_ms(timeout); + } + Config(words_from_bytes(&capnp::serialize::write_message_to_words( + &message, + ))) +} + +/// The cluster's `stopTimeoutMs` in `config`. +fn stop_timeout_of(config: &Config) -> u32 { + read(config) + .get_root::() + .unwrap() + .get_cluster() + .unwrap() + .get_stop_timeout_ms() +} + +#[test] +fn cluster_stop_timeout_in_environment_overrides_config() { + for configured in [None, Some(20_000)] { + for (value, timeout) in [ + ("30000", 30_000), + ("8000", 8000), + ("0", 0), + ("3600000", 3_600_000), + // Trailing whitespace, such as a file's final newline, is trimmed. + ("30000\n", 30_000), + ] { + let config = stop_timeout_config(configured) + .fill(env(&[(CLUSTER_STOP_TIMEOUT_MS, value)])) + .unwrap(); + assert_eq!( + stop_timeout_of(&config), + timeout, + "{configured:?} {value:?}" + ); + // The rest of the cluster is kept. + assert_eq!( + cluster_of(&config), + (KEY.to_owned(), "s3://bucket/prefix".to_owned()) + ); + } + } +} + +#[test] +fn cluster_stop_timeout_unset_or_blank_in_environment_keeps_config() { + for configured in [None, Some(20_000)] { + for vars in [vec![], vec![(CLUSTER_STOP_TIMEOUT_MS, " \n")]] { + let config = stop_timeout_config(configured); + let before = config.0.clone(); + let config = config.fill(env(&vars)).unwrap(); + assert_eq!(config.0, before, "{configured:?} {vars:?}"); + } + } +} + +#[test] +fn unusable_cluster_stop_timeout_in_environment_is_an_error() { + for value in [ + "abc", + "-1", + "+20", + "1.5", + "8s", + " 20", + "3600001", + "99999999999", + ] { + for configured in [None, Some(20_000)] { + let Err(error) = + stop_timeout_config(configured).fill(env(&[(CLUSTER_STOP_TIMEOUT_MS, value)])) + else { + panic!("{value:?} accepted over {configured:?}"); + }; + assert_eq!( + error, + format!( + "WORKERD_CLUSTER_STOP_TIMEOUT_MS={value}: not a whole number of milliseconds \ + from 0 to 3600000 (an hour)." + ) + ); + } + } +} + +#[test] +fn cluster_stop_timeout_applies_to_a_joined_cluster_only_with_a_cluster() { + let vars = [ + (CLUSTER_KEY, KEY), + (CLUSTER_BUCKET, "s3://bucket/prefix"), + (CLUSTER_STOP_TIMEOUT_MS, "30000"), + ]; + let var = env(&vars); + let flags = ClusterFlags { + address: Some("10.0.0.4:7000"), + advertise: None, + can_join: true, + }; + let config = joinable_config().with_cluster(&flags, Some(&var)).unwrap(); + assert_eq!(stop_timeout_of(&config), 30_000); + + // A config that joins no cluster is unchanged. + let config = cluster_config(None); + let before = config.0.clone(); + let config = config.fill(env(&vars)).unwrap(); + assert_eq!(config.0, before); +} + #[test] fn a_config_without_cluster_storage_cannot_join_a_cluster() { let expected = "--cluster-addr: the config has no writable disk service named `do-storage`, \ @@ -506,3 +626,146 @@ fn a_compiled_config_without_cluster_cannot_join_one() { let before = config.0.clone(); assert_eq!(config.with_cluster(&flags, None).unwrap().0, before); } + +/// A config with `shutdownDelayMs` set to `delay`. +fn shutdown_delay_config(delay: u32) -> Config { + let mut message = capnp::message::Builder::new_default(); + let mut root = message.init_root::(); + root.reborrow().init_services(1).get(0).set_name("main"); + root.set_shutdown_delay_ms(delay); + Config(words_from_bytes(&capnp::serialize::write_message_to_words( + &message, + ))) +} + +/// The `shutdownDelayMs` of `config`. +fn shutdown_delay_of(config: &Config) -> u32 { + let message = read(config); + let root = message.get_root::().unwrap(); + // The rest of the config is kept. + assert_eq!( + root.get_services().unwrap().get(0).get_name().unwrap(), + "main" + ); + root.get_shutdown_delay_ms() +} + +/// An environment where `SHUTDOWN_DELAY_MS` is `value`, if any. +fn shutdown_delay_env(value: Option<&str>) -> impl Fn(&str) -> Option + '_ { + move |name| { + assert_eq!(name, SHUTDOWN_DELAY_MS); + value.map(OsString::from) + } +} + +#[test] +fn shutdown_delay_unset_or_blank_in_environment_keeps_the_config_delay() { + for configured in [0, 5000] { + for value in [None, Some(""), Some(" \n")] { + let config = shutdown_delay_config(configured) + .with_shutdown_delay_environment(shutdown_delay_env(value)) + .unwrap(); + assert_eq!(shutdown_delay_of(&config), configured, "{value:?}"); + } + } +} + +#[test] +fn shutdown_delay_comes_from_environment() { + for (value, delay) in [ + ("20000", 20_000), + ("0", 0), + ("3600000", 3_600_000), + // Trailing whitespace, such as a file's final newline, is trimmed. + ("20000\n", 20_000), + ("20000 \t", 20_000), + ] { + let config = shutdown_delay_config(0) + .with_shutdown_delay_environment(shutdown_delay_env(Some(value))) + .unwrap(); + assert_eq!(shutdown_delay_of(&config), delay, "{value:?}"); + } +} + +#[test] +fn shutdown_delay_in_environment_overrides_config() { + for (configured, value, delay) in [ + (5000, "20000", 20_000), + (5000, "5000", 5000), + (5000, "0", 0), + // A delay the config cannot have is no error when the variable overrides it. + (20_000_000, "5000", 5000), + ] { + let config = shutdown_delay_config(configured) + .with_shutdown_delay_environment(shutdown_delay_env(Some(value))) + .unwrap(); + assert_eq!(shutdown_delay_of(&config), delay, "{configured} {value:?}"); + } +} + +#[test] +fn unusable_shutdown_delay_in_environment_is_an_error() { + for value in [ + "abc", + "-1", + "+20", + "1.5", + "20s", + " 20", + "2 0", + "3600001", + "99999999999", + ] { + // Even where the config sets a delay, which the variable would override. + for configured in [0, 5000] { + let Err(error) = shutdown_delay_config(configured) + .with_shutdown_delay_environment(shutdown_delay_env(Some(value))) + else { + panic!("{value:?} accepted over {configured}"); + }; + assert_eq!( + error, + format!( + "WORKERD_SHUTDOWN_DELAY_MS={value}: not a whole number of milliseconds \ + from 0 to 3600000 (an hour)." + ) + ); + } + } +} + +#[cfg(unix)] +#[test] +fn shutdown_delay_in_environment_that_is_not_utf8_is_an_error() { + use std::os::unix::ffi::OsStringExt; + + let var = |name: &str| { + assert_eq!(name, SHUTDOWN_DELAY_MS); + Some(OsString::from_vec(b"20\xff".to_vec())) + }; + let Err(error) = shutdown_delay_config(0).with_shutdown_delay_environment(var) else { + panic!("accepted"); + }; + assert_eq!( + error, + "WORKERD_SHUTDOWN_DELAY_MS=20\u{fffd}: not UTF-8 text." + ); +} + +#[test] +fn shutdown_delay_above_an_hour_in_config_is_an_error() { + let config = shutdown_delay_config(3_600_000) + .with_shutdown_delay_environment(shutdown_delay_env(None)) + .unwrap(); + assert_eq!(shutdown_delay_of(&config), 3_600_000); + + let Err(error) = + shutdown_delay_config(20_000_000).with_shutdown_delay_environment(shutdown_delay_env(None)) + else { + panic!("accepted"); + }; + assert_eq!( + error, + "Config.shutdownDelayMs = 20000000: more than 3600000 (an hour)." + ); +} diff --git a/src/workerd/server/cli/config.rs b/src/workerd/server/cli/config.rs index 48e26726d34..bdd3d0e5038 100644 --- a/src/workerd/server/cli/config.rs +++ b/src/workerd/server/cli/config.rs @@ -3,6 +3,7 @@ //! executable. Every source is checked to be a well-formed `Config` message here, and ends up as //! a [`Config`] for the C++ driver. +use std::ffi::OsString; use std::fmt; use std::fs::File; use std::io; @@ -90,10 +91,13 @@ impl Config { /// `--cluster-addr` overrides its address. A config without either is unchanged, and then /// `flags.advertise`, the value of `--cluster-advertise`, is an error. /// - /// Then, with `var`, the cluster's `key` and `bucket` are taken from the environment where it - /// sets them, over the config's. See `ClusterConfig` in workerd.capnp. `var` reads an + /// Then, with `var`, the cluster's `key`, `bucket` and `stopTimeoutMs` are taken from the + /// environment where it sets them, over the config's: the key and bucket from + /// [`CLUSTER_KEY`] or [`CLUSTER_KEY_FILE`] and [`CLUSTER_BUCKET`], the stop timeout from + /// [`CLUSTER_STOP_TIMEOUT_MS`]. See `ClusterConfig` in workerd.capnp. `var` reads an /// environment variable and returns `None` when it is unset or empty. A key or bucket that - /// neither the environment nor the config sets is an error. + /// neither the environment nor the config sets, and a stop timeout variable that is not a + /// whole number of milliseconds up to `MAX_STOP_TIMEOUT_MS`, is an error. pub fn with_cluster( self, flags: &ClusterFlags<'_>, @@ -135,8 +139,8 @@ impl Config { (None, None) => return Ok(self), } }; - let (key, bucket) = match var { - None => (None, None), + let (key, bucket, stop_timeout) = match var { + None => (None, None, None), Some(var) => { // A joined config's cluster is new, so its key and bucket are empty. let (key_empty, bucket_empty) = if join.is_some() { @@ -149,11 +153,18 @@ impl Config { }; (empty(cluster.get_key())?, empty(cluster.get_bucket())?) }; - cluster_environment(var, key_empty, bucket_empty) - .map_err(ClusterError::Environment)? + let (key, bucket) = cluster_environment(var, key_empty, bucket_empty) + .map_err(ClusterError::Environment)?; + let stop_timeout = milliseconds( + CLUSTER_STOP_TIMEOUT_MS, + var(CLUSTER_STOP_TIMEOUT_MS).map(OsString::from), + MAX_STOP_TIMEOUT_MS, + ) + .map_err(ClusterError::Environment)?; + (key, bucket, stop_timeout) } }; - if join.is_none() && key.is_none() && bucket.is_none() { + if join.is_none() && key.is_none() && bucket.is_none() && stop_timeout.is_none() { return Ok(self); } let mut message = capnp::message::Builder::new_default(); @@ -173,6 +184,53 @@ impl Config { if let Some(bucket) = bucket { cluster.set_bucket(bucket.as_str()); } + if let Some(timeout) = stop_timeout { + cluster.set_stop_timeout_ms(timeout); + } + Ok(Self(words_from_bytes( + &capnp::serialize::write_message_to_words(&message), + ))) + } + + /// Takes `shutdownDelayMs` from `SHUTDOWN_DELAY_MS` where that is set, over the config's, then + /// checks it. See `Config` in workerd.capnp. `var` reads an environment variable. A variable + /// that is unset, or empty once trailing whitespace is trimmed, leaves the config's delay. One + /// that is not UTF-8 or not a whole number of milliseconds, and a delay above + /// `MAX_SHUTDOWN_DELAY_MS` from either source, is an error. + pub fn with_shutdown_delay_environment( + self, + var: impl Fn(&str) -> Option, + ) -> Result { + let bytes = self.to_bytes(); + let message = capnp::serialize::read_message(bytes.as_slice(), reader_options()) + .map_err(|error| error.to_string())?; + let root = message + .get_root::() + .map_err(|error| error.to_string())?; + let configured = root.get_shutdown_delay_ms(); + let Some(delay) = milliseconds( + SHUTDOWN_DELAY_MS, + var(SHUTDOWN_DELAY_MS), + MAX_SHUTDOWN_DELAY_MS, + )? + else { + if configured > MAX_SHUTDOWN_DELAY_MS { + return Err(format!( + "Config.shutdownDelayMs = {configured}: more than {MAX_SHUTDOWN_DELAY_MS} \ + (an hour)." + )); + } + return Ok(self); + }; + if delay == configured { + return Ok(self); + } + let mut message = capnp::message::Builder::new_default(); + message.set_root(root).map_err(|error| error.to_string())?; + message + .get_root::() + .map_err(|error| error.to_string())? + .set_shutdown_delay_ms(delay); Ok(Self(words_from_bytes( &capnp::serialize::write_message_to_words(&message), ))) @@ -332,6 +390,49 @@ fn read_key_file(path: &str) -> Result { String::from_utf8(key).map_err(|_| "not UTF-8 text. The key must be text.".to_owned()) } +/// The environment variable that holds the shutdown delay, over the config's. +pub const SHUTDOWN_DELAY_MS: &str = "WORKERD_SHUTDOWN_DELAY_MS"; + +/// The largest shutdown delay, set in the config or in `SHUTDOWN_DELAY_MS`. The delay waits out +/// load balancers that still send connections, which takes seconds, so a larger value is a +/// mistake, such as a value in microseconds, that would leave a stopping process serving for days +/// and a cluster node killed by its supervisor before it hands its Durable Objects off. +const MAX_SHUTDOWN_DELAY_MS: u32 = 3_600_000; + +/// The environment variable that holds the cluster's stop timeout, over the config's. +pub const CLUSTER_STOP_TIMEOUT_MS: &str = "WORKERD_CLUSTER_STOP_TIMEOUT_MS"; + +/// The largest stop timeout in `CLUSTER_STOP_TIMEOUT_MS`. A stop takes seconds, so a larger value +/// is a mistake, such as a value in microseconds, that would leave a stopping node waiting for +/// days on a request that does not end. +const MAX_STOP_TIMEOUT_MS: u32 = 3_600_000; + +/// The milliseconds in `value`, the value of the environment variable `name`, without trailing +/// whitespace such as a final newline: digits only, up to `max`, an hour for each caller, as the +/// error says. `None` when it is unset or blank. +fn milliseconds(name: &str, value: Option, max: u32) -> Result, String> { + let Some(value) = value else { + return Ok(None); + }; + let value = value + .into_string() + .map_err(|value| format!("{name}={}: not UTF-8 text.", value.to_string_lossy()))?; + let digits = value.trim_end(); + if digits.is_empty() { + return Ok(None); + } + digits + .bytes() + .all(|byte| byte.is_ascii_digit()) + .then(|| digits.parse::().ok()) + .flatten() + .filter(|ms| *ms <= max) + .map(Some) + .ok_or_else(|| { + format!("{name}={value}: not a whole number of milliseconds from 0 to {max} (an hour).") + }) +} + /// Configs can legitimately be very large and are not malicious, so use an effectively-infinite /// traversal limit. fn reader_options() -> ReaderOptions { diff --git a/src/workerd/server/cli/help.rs b/src/workerd/server/cli/help.rs index b2c25927962..f67bef97b6e 100644 --- a/src/workerd/server/cli/help.rs +++ b/src/workerd/server/cli/help.rs @@ -49,9 +49,26 @@ Cluster (experimental): AWS_* variables; gs:// buckets, GOOGLE_APPLICATION_CREDENTIALS. WORKERD_CLUSTER_KEY, or the file that WORKERD_CLUSTER_KEY_FILE names, overrides the config's cluster key, WORKERD_CLUSTER_BUCKET its bucket. - On SIGTERM an instance hands its objects to its peers and exits within + On SIGTERM, after any shutdown delay, an instance hands its objects to + its peers and exits within WORKERD_CLUSTER_STOP_TIMEOUT_MS, or else stopTimeoutMs (8 s by default). GET /ready on the cluster address - answers OK once serving. + answers OK once serving, until SIGTERM. +" + }; +} + +macro_rules! stopping { + () => { + "\ +Stopping: + On SIGTERM the server drains: it stops accepting connections, lets + the open ones finish, and exits. WORKERD_SHUTDOWN_DELAY_MS, or else + shutdownDelayMs in the config, keeps it serving that many + milliseconds first, for load balancers that go on sending connections + for a while; a second SIGTERM drains at once. The supervisor's grace + period must cover the delay and the drain, in a cluster the delay + plus stopTimeoutMs. A cluster instance's GET /ready answers 503 from + the first SIGTERM on. " }; } @@ -215,6 +232,8 @@ Usage: "\n", capnp_options!(), "\n", + stopping!(), + "\n", cluster_setup!(), ); @@ -378,6 +397,8 @@ Options: trace_options!(), "\n", python_options!(), + "\n", + stopping!(), ); pub const FUZZILLI: &str = concat!( diff --git a/src/workerd/server/cli/lib.rs b/src/workerd/server/cli/lib.rs index 0e536b293f2..136c6b045fb 100644 --- a/src/workerd/server/cli/lib.rs +++ b/src/workerd/server/cli/lib.rs @@ -108,6 +108,7 @@ fn run_compiled( let watcher = watcher::(&args.serve_or_test, executable.as_ref()); let (options, inherited_sockets) = serve_options::(args.serve, &args.serve_or_test); let process = Process::new(executable, watcher, inherited_sockets); + let config = with_environment(config); let (config, options) = with_cluster::(config, &args.serve_or_test, options, &process, false); entry::serve( @@ -143,6 +144,7 @@ fn run_command(args: args::Main, executable: Option) -> workerd_serv serve_or_test.data_dir.as_deref(), serve_or_test.experimental, ); + let config = with_environment(config); let (config, options) = with_cluster::(config, &serve_or_test, options, &process, true); entry::serve( @@ -510,10 +512,38 @@ fn load_config( config_errors(&compiled.errors, process) } +/// Overrides settings in `config` with those the environment sets, for `serve` and a compiled +/// binary only, so that `compile` never embeds the environment, and checks them. An +/// unusable variable or setting ends the process, even under `--watch`, because the cause can lie +/// outside the config files. +fn with_environment(config: Config) -> Config { + config + .with_shutdown_delay_environment(|name: &str| std::env::var_os(name)) + .unwrap_or_else(|error| { + eprintln!("{error}"); + std::process::exit(1); + }) +} + +/// The value of the environment variable `name` for [`Config::with_cluster`]: `None` when it is +/// unset or empty. One that is not UTF-8 ends the process, as an unusable +/// `WORKERD_SHUTDOWN_DELAY_MS` does, rather than count as unset. +fn cluster_var(name: &str) -> Option { + match std::env::var(name) { + Ok(value) => Some(value).filter(|value| !value.is_empty()), + Err(std::env::VarError::NotPresent) => None, + // The value is not shown: it may be the cluster key. + Err(std::env::VarError::NotUnicode(_)) => { + eprintln!("{name}: not UTF-8 text."); + std::process::exit(1); + } + } +} + /// Joins `config` to a cluster with `--cluster-addr` if it has none, `can_join` (not for a -/// compiled config) and a writable disk service `do-storage`, fills its cluster key and bucket -/// from the environment ([`Config::with_cluster`]), then adds cluster deployments to `config` and -/// records their service sources in `options`. +/// compiled config) and a writable disk service `do-storage`, takes its cluster key, bucket and +/// stop timeout from the environment where it sets them ([`Config::with_cluster`]), then adds +/// cluster deployments to `config` and records their service sources in `options`. /// /// Only joining happens without `--experimental`, so that the server refuses the cluster as it /// refuses one in the config. A public cluster address or an error in `config` found during @@ -533,8 +563,9 @@ fn with_cluster( advertise: options.cluster_advertise.as_deref(), can_join, }; - let var = |name: &str| std::env::var(name).ok().filter(|value| !value.is_empty()); - let environment = serve_or_test.experimental.then_some(&var as Env<'_>); + let environment = serve_or_test + .experimental + .then_some(&cluster_var as Env<'_>); let config = match config.with_cluster(&flags, environment) { Ok(config) => config, Err(ClusterError::Usage(error)) => usage_error::(error), diff --git a/src/workerd/server/cluster/compose-test.rs b/src/workerd/server/cluster/compose-test.rs index d70f4015497..d548a2b6f8d 100644 --- a/src/workerd/server/cluster/compose-test.rs +++ b/src/workerd/server/cluster/compose-test.rs @@ -219,6 +219,10 @@ fn a_deployment_may_contain_only_services() { "deployment \"app\" sets `sockets`, `structuredLogging`, `cluster`. A deployment may \ contain only `services`. Put other settings in the instance's config." ); + let config = build(&[("app", WORKER)], |mut root| { + root.set_shutdown_delay_ms(20_000); + }); + assert!(refusal(deployment_config("app", &config)).contains("sets `shutdownDelayMs`")); let config = build(&[("app", WORKER)], |root| { root.init_extensions(0); }); diff --git a/src/workerd/server/cluster/compose.rs b/src/workerd/server/cluster/compose.rs index c434c1d97b8..148f0aba88e 100644 --- a/src/workerd/server/cluster/compose.rs +++ b/src/workerd/server/cluster/compose.rs @@ -8,10 +8,10 @@ //! deployment in catalog order. [`merge`] skips a deployment as a whole when it breaks a rule. //! //! - A deployment holds only `services`. Every other field of `Config` (sockets, the cluster -//! block, extensions, V8 flags, autogates, logging) is the node's, and a deployment that sets -//! one is skipped rather than trimmed. So is one that defines a `disk` service, whose path is -//! the node's, or a service named `internet`, which would replace the node's implicit one for -//! every worker. +//! block, extensions, V8 flags, autogates, logging, the shutdown delay) is the node's, and a +//! deployment that sets one is skipped rather than trimmed. So is one that defines a `disk` +//! service, whose path is the node's, or a service named `internet`, which would replace the +//! node's implicit one for every worker. //! - Service names are unique across the node's config and every deployment, and so are the keys //! of actor namespaces: Durable Object `uniqueKey`s and the key of each Workflow's namespace //! (`workflow_namespace_key`). A deployment refers to what the node provides, such as the disk @@ -350,6 +350,7 @@ fn check_deployment( ("structuredLogging", config.get_structured_logging()), ("logging", config.has_logging()), ("cluster", config.has_cluster()), + ("shutdownDelayMs", config.get_shutdown_delay_ms() != 0), ]; let set: Vec<_> = node_fields .iter() diff --git a/src/workerd/server/server-test.c++ b/src/workerd/server/server-test.c++ index dcc2ea65041..46ef02b7e6b 100644 --- a/src/workerd/server/server-test.c++ +++ b/src/workerd/server/server-test.c++ @@ -443,6 +443,11 @@ class Server: public kj::PtrTarget { .attach(kj::mv(drain), reports(server)); } + // Sends the server the drain signal, as SIGTERM does. + void drain() { + get().drain(); + } + kj::Promise test(jsg::V8System& v8System, config::Config::Reader config, kj::StringPtr servicePattern, @@ -5793,6 +5798,105 @@ KJ_TEST("Server: drain incoming HTTP connections") { KJ_EXPECT(conn2.isEof()); } +// A worker that answers "hello" on "test-addr", served with `shutdownDelayMs` set to `delayMs`. +kj::String helloWithShutdownDelay(kj::StringPtr delayMs) { + return kj::str(R"(( + services = [ + ( name = "hello", + worker = ( + compatibilityDate = "2022-08-17", + serviceWorkerScript = + `addEventListener("fetch", event => { + ` event.respondWith(new Response("hello")); + `}) + ) + ) + ], + sockets = [ + ( name = "main", + address = "test-addr", + service = "hello" + ) + ], + shutdownDelayMs = )"_kj, + delayMs, R"( + ))"_kj); +} + +KJ_TEST("Server: the shutdown delay serves on after the drain signal, then drains") { + TestServer test(helloWithShutdownDelay("20000")); + test.start(); + + auto conn = test.connect("test-addr"); + conn.httpGet200("/", "hello"); + + test.server.drain(); + + // Until the delay ends, open connections and new ones are served as before. + conn.httpGet200("/", "hello"); + KJ_EXPECT(!conn.isEof()); + test.wait(19); + conn.httpGet200("/", "hello"); + auto conn2 = test.connect("test-addr"); + conn2.httpGet200("/", "hello"); + conn2.send("GET"); + + // Then the server drains: idle connections close, the one with a request in progress finishes + // it, and new ones are not accepted. + test.wait(1); + KJ_EXPECT(conn.isEof()); + KJ_EXPECT(!conn2.isEof()); + KJ_EXPECT(test.connectHangs("test-addr")); + conn2.send(" / HTTP/1.1\nHost: foo\n\n"); + conn2.recv(R"( + HTTP/1.1 200 OK + Connection: close + Content-Length: 5 + Content-Type: text/plain;charset=UTF-8 + + hello)"_blockquote); + KJ_EXPECT(conn2.isEof()); +} + +KJ_TEST("Server: a second drain signal cuts the shutdown delay short") { + TestServer test(helloWithShutdownDelay("1000000")); + test.start(); + + auto conn = test.connect("test-addr"); + auto conn2 = test.connect("test-addr"); + test.server.drain(); + conn.httpGet200("/", "hello"); + conn2.httpGet200("/", "hello"); + conn2.send("GET"); + KJ_EXPECT(!conn.isEof()); + + test.server.drain(); + KJ_EXPECT(conn.isEof()); + KJ_EXPECT(!conn2.isEof()); + KJ_EXPECT(test.connectHangs("test-addr")); + conn2.send(" / HTTP/1.1\nHost: foo\n\n"); + conn2.recv(R"( + HTTP/1.1 200 OK + Connection: close + Content-Length: 5 + Content-Type: text/plain;charset=UTF-8 + + hello)"_blockquote); + KJ_EXPECT(conn2.isEof()); +} + +KJ_TEST("Server: a drain signal sent before the server serves drains it at once") { + TestServer test(helloWithShutdownDelay("20000")); + // `run()` creates the server, which starts once the promise is polled: the signal is pending + // as it starts, as a SIGTERM that arrives while the process starts is. + auto run = test.server.run(v8System, *test.config); + test.server.drain(); + + // With no connections to finish, the run ends without the timer advancing. + KJ_EXPECT(run.poll(test.ws)); + run.wait(test.ws); +} + // ======================================================================================= // Test alternate service types // diff --git a/src/workerd/server/server/cluster.rs b/src/workerd/server/server/cluster.rs index a61da2e81ac..435e139ada4 100644 --- a/src/workerd/server/server/cluster.rs +++ b/src/workerd/server/server/cluster.rs @@ -10,7 +10,7 @@ //! whose `getActor` gives a `WorkerdBootstrap` for one Durable Object, so HTTP, WebSockets and //! JS RPC to the object cross unchanged. A request for an object this instance //! does not own routes on through its own channel to the owner. `GET /ready` answers whether -//! the instance takes traffic: it serves, holds its lease, and is not stopping. +//! the instance takes traffic: it serves, holds its lease, and was not told to stop. use std::cell::Cell; use std::cell::RefCell; @@ -99,14 +99,15 @@ pub struct ClusterNode { /// Set once this instance stops its peers' sessions (`stop_peer_sessions`): from then on it /// starts none of their requests, and accepts no session. refusing_peers: Rc, - /// Whether the application's listeners are being served (`Serving`). - serving: Cell, + /// Whether the application's listeners are served and the instance was not told to stop + /// (`Ready`). + ready: Cell, /// How long a stop waits from its drain's start to leave: the leases a service granted /// here (the cache's), else 0. pub leave_wait_ms: Cell, /// The `cache` services a peer's session reaches here (`ServerHandle::resolve_peer_cache`). pub caches: RefCell>, - /// Whether the lease thread watches this thread's event loop (`serving`). + /// Whether the lease thread watches this thread's event loop (`ready`). watched: Cell, /// How often the event loop counts its progress while it sleeps: once a lease round. beat: Duration, @@ -134,12 +135,13 @@ pub struct Count { none: Notify, } -/// The application's listeners are being served, until this is dropped. -pub struct Serving(Rc); +/// The instance takes traffic as far as its listeners go, until this is dropped: they are served, +/// and it was not told to stop. +pub struct Ready(Rc); -impl Drop for Serving { +impl Drop for Ready { fn drop(&mut self) { - self.0.serving.set(false); + self.0.ready.set(false); } } @@ -557,7 +559,7 @@ impl ClusterNode { peer_requests: Rc::default(), peer_sessions: Rc::default(), refusing_peers: Rc::default(), - serving: Cell::new(false), + ready: Cell::new(false), leave_wait_ms: Cell::new(0), caches: RefCell::default(), watched: Cell::new(false), @@ -565,11 +567,12 @@ impl ClusterNode { })) } - /// Marks the application's listeners as served until the guard is dropped. + /// Marks the instance as taking traffic, as far as its listeners go, until the guard is + /// dropped. /// /// The first time, the lease thread starts watching this thread's event loop /// (`Cluster::watch`). Not before: linking runs in turns as long as itself. - pub fn serving(self: &Rc) -> Serving { + pub fn ready(self: &Rc) -> Ready { if !self.watched.replace(true) { // The loop beats once a round while it sleeps. A loop that cannot be watched serves // on, and says that it does; what stops it from being watched lasts, so it is not @@ -582,8 +585,8 @@ impl ClusterNode { ), } } - self.serving.set(true); - Serving(Rc::clone(self)) + self.ready.set(true); + Ready(Rc::clone(self)) } /// Starts draining: this instance claims nothing more, and its stop's deadlines run from now. @@ -990,9 +993,10 @@ impl Handler for PeerConnection { if method != Method::GET || url != b"/ready" { return send_error(response, 404, "Not Found", &headers).await; } - // Ready to take traffic: serving, a member of the cluster, not stopping. + // Ready to take traffic: serving and not told to stop, a member of the cluster, not + // draining. let cluster = &self.node.cluster; - if self.node.serving.get() && cluster.lease_holds() && !cluster.is_draining() { + if self.node.ready.get() && cluster.lease_holds() && !cluster.is_draining() { send_error(response, 200, "OK", &headers).await } else { send_error(response, 503, "Service Unavailable", &headers).await diff --git a/src/workerd/server/server/config.rs b/src/workerd/server/server/config.rs index 88a2d943ce2..3bed5c491bf 100644 --- a/src/workerd/server/server/config.rs +++ b/src/workerd/server/server/config.rs @@ -1534,7 +1534,7 @@ impl Server { if let Some(cluster) = &cluster { // Actor databases open only under a lease, which the lease thread keeps from here on, // however long linking takes: it watches the event loop only once the node serves - // (`ClusterNode::serving`). + // (`ClusterNode::ready`). cluster .cluster .join() diff --git a/src/workerd/server/server/entry.rs b/src/workerd/server/server/entry.rs index b483b474fea..8b9fed9df20 100644 --- a/src/workerd/server/server/entry.rs +++ b/src/workerd/server/server/entry.rs @@ -26,6 +26,7 @@ use std::rc::Rc; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; +use futures::Stream; use futures::future::Either; use futures::future::LocalBoxFuture; use kj_rs::KjOwn; @@ -213,26 +214,32 @@ async fn with_watch( } } -/// Resolves on SIGTERM, or on Windows on Ctrl-Break (`CTRL_BREAK_EVENT`, the console event a -/// parent can send a process group, where Ctrl-C is the interactive interrupt): the signal to -/// drain gracefully. The handler is installed by the call, so that a signal during startup drains -/// the server once it is up. -fn sigterm() -> impl Future { +/// SIGTERM, or on Windows Ctrl-Break (`CTRL_BREAK_EVENT`, the console event a parent can send a +/// process group, where Ctrl-C is the interactive interrupt): the signal to drain gracefully, each +/// time it arrives. Signals that arrive before the stream is polled again count as one. The +/// handler is installed by the call, so that a signal during startup is pending once the server +/// is up. +fn sigterm() -> impl Stream { #[cfg(unix)] let signal = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()); #[cfg(windows)] let signal = tokio::signal::windows::ctrl_break(); - async move { - match signal { - Ok(mut signal) => { - signal.recv().await; - } - Err(e) => { - tracing::error!("drain signal handler: {e}"); - std::future::pending::<()>().await; - } + let signal = match signal { + Ok(signal) => Some(signal), + Err(e) => { + tracing::error!("drain signal handler: {e}"); + None } - } + }; + // Without a handler the stream waits forever rather than end. Once the handler stops + // receiving (`recv()` answers `None`), it yields one last signal, then waits forever. + futures::stream::unfold(signal, |signal| async move { + let Some(mut signal) = signal else { + return std::future::pending().await; + }; + let received = signal.recv().await; + Some(((), received.map(|()| signal))) + }) } /// `workerd serve`: serves `factory`'s config until SIGTERM drains it (or a `--watch` reload diff --git a/src/workerd/server/server/in_process.rs b/src/workerd/server/server/in_process.rs index 1ee7786cb44..cb738f69715 100644 --- a/src/workerd/server/server/in_process.rs +++ b/src/workerd/server/server/in_process.rs @@ -110,7 +110,11 @@ impl InProcessServer { ..RunOptions::default() }; let factory = Rc::clone(&self.factory); - crate::run::run(factory, options, self.reporter(), self.drain.notified()).await + let drain = futures::stream::unfold(&self.drain, |drain| async move { + drain.notified().await; + Some(((), drain)) + }); + crate::run::run(factory, options, self.reporter(), drain).await } /// `workerd test`. @@ -149,6 +153,9 @@ impl InProcessServer { }) } + /// The drain signal, SIGTERM in `workerd serve`. Sent before [`Self::run`], or while the + /// server starts, it is pending once the server is up, as a SIGTERM that arrives while the + /// process starts is. pub fn drain(&self) { self.drain.notify_one(); } diff --git a/src/workerd/server/server/run.rs b/src/workerd/server/server/run.rs index 86a42d3016e..cce6d6c54a2 100644 --- a/src/workerd/server/server/run.rs +++ b/src/workerd/server/server/run.rs @@ -8,10 +8,12 @@ use std::collections::HashMap; use std::future::Future; use std::io::Write; +use std::pin::Pin; use std::rc::Rc; use std::time::Duration; use futures::FutureExt; +use futures::Stream; use futures::StreamExt; use futures::future::Either; use futures::future::FusedFuture; @@ -34,6 +36,7 @@ use crate::bridge::ffi; use crate::channels::Channel; use crate::cluster; use crate::cluster::ClusterNode; +use crate::cluster::Ready; use crate::config::Deployments; use crate::config::Factory; use crate::config::Overrides; @@ -424,19 +427,24 @@ async fn serve_listeners( Ok(()) } -/// `workerd serve`: serves until `drain` resolves, then stops accepting connections, lets the -/// open ones finish, and stops the actors' containers. A listener failing is fatal and is the -/// error returned. +/// `workerd serve`: serves until told to drain, then stops accepting connections, lets the open +/// ones finish, and stops the actors' containers. A listener failing is fatal and is the error +/// returned. +/// +/// Each item of `drain`, which never ends, is a drain signal. After the first, the server serves +/// on for the config's `shutdownDelayMs`, or until the next signal, then drains (`drain_due`). /// /// In a cluster, the instance first hands its Durable Objects off while it keeps serving, then /// leaves the cluster, and accepts requests for a grace period at least; the cluster's -/// `stopTimeoutMs` bounds all of it. +/// `stopTimeoutMs` bounds all of it, from the end of the shutdown delay. +#[expect(clippy::too_many_lines, reason = "a server's life, from start to stop")] pub async fn run( factory: Rc, options: RunOptions, report: Reporter, - drain: impl Future, + drain: impl Stream, ) -> Result<()> { + let delay = shutdown_delay(&factory)?; let Some(Running { server, mut listeners, @@ -446,10 +454,16 @@ pub async fn run( return Ok(()); }; - // From here on the lease thread watches the event loop. Whatever way this returns, the - // cluster port answers that this instance is not ready. - let _serving = server.cluster().map(ClusterNode::serving); - let drain = std::pin::pin!(drain); + // A SIGTERM that arrived while the server started reaches `drain` only once the runtime has + // polled its drivers, which a start that never had to wait may not have let it do. tokio wakes + // a task that yields only after it has polled them, so the check below sees such a signal. + tokio::task::yield_now().await; + let mut drain = std::pin::pin!(drain); + let pending = drain.next().now_or_never().is_some(); + // From here on the lease thread watches the event loop. The cluster port answers ready + // until the instance is told to drain or this returns. + let ready = server.cluster().map(ClusterNode::ready); + let drain = std::pin::pin!(drain_due(server.factory(), delay, pending, ready, drain)); let mut serving = std::pin::pin!(serve_listeners(&mut listeners).fuse()); let mut stop = None; // Draining stops the accept loops; the listeners then end once their connections have. @@ -556,6 +570,44 @@ pub async fn run( Ok(()) } +/// The config's `shutdownDelayMs`. +fn shutdown_delay(factory: &Factory) -> Result { + let message = factory.config()?; + let config = message.get_root::().map_err(capnp_error)?; + Ok(Duration::from_millis(config.get_shutdown_delay_ms().into())) +} + +/// Resolves when `run` is to drain. That is at once if a signal was `pending` as the server +/// started: it was never ready, so nothing sends it traffic to serve through the delay. Otherwise +/// it is `delay` (`Config.shutdownDelayMs`) after the next item of `drain`, or on the item after +/// it, whichever comes first. Load balancers go on sending connections for a while, which are +/// served as before meanwhile, and a cluster node keeps its Durable Objects and its place in the +/// cluster. Its readiness probe fails from the signal on (`ready` is dropped), so that what routes +/// by it sends no more. +async fn drain_due( + factory: &Factory, + delay: Duration, + pending: bool, + ready: Option, + mut drain: Pin<&mut impl Stream>, +) { + if pending { + return; + } + drain.next().await; + drop(ready); + if delay.is_zero() { + return; + } + let seconds = delay.as_secs_f64(); + tracing::warn!( + "drain signal received: serving for {seconds:.1} s more (shutdownDelayMs), then \ + draining; a second signal drains at once" + ); + let delay = std::pin::pin!(factory.sleep(delay)); + futures::future::select(delay, drain.next()).await; +} + /// An entrypoint `workerd test` or `workerd bench` runs a handler of. struct Target { channel: Rc, diff --git a/src/workerd/server/tests/cluster/cluster-test.mjs b/src/workerd/server/tests/cluster/cluster-test.mjs index ac0a0e27a2d..ff854cab8e8 100644 --- a/src/workerd/server/tests/cluster/cluster-test.mjs +++ b/src/workerd/server/tests/cluster/cluster-test.mjs @@ -367,6 +367,12 @@ class ClusterNode { return result; } + // Sends the node `signal` without waiting for it to exit. + signal(signal) { + assert(this.#child !== null, 'node not started'); + this.#child.kill(signal); + } + async stop({ signal = 'SIGTERM', timeoutMs = 10_000 } = {}) { if (this.#child === null) return null; const child = this.#child; @@ -3117,6 +3123,202 @@ test( } ); +// The status of `GET /ready` on a cluster port, or undefined once nothing +// answers within a second. +async function readiness(port) { + const signal = AbortSignal.timeout(1000); + return ( + await fetch(`http://127.0.0.1:${port}/ready`, { signal }).catch(() => null) + )?.status; +} + +// The first status other than 200 that `GET /ready` on a cluster port +// answers, within `ms`. +async function untilNotReady(port, ms = 5000) { + const deadline = Date.now() + ms; + for (;;) { + const status = await readiness(port); + if (status !== 200) return status; + assert(Date.now() < deadline, `port ${port} still ready after ${ms} ms`); + await sleep(20); + } +} + +// The shutdown delay, in seconds, of the nodes in the tests below, which +// WORKERD_SHUTDOWN_DELAY_MS sets. +const SHUTDOWN_DELAY_S = 6; + +test( + 'cluster: a node serves its DOs through its shutdown delay, then hands them off', + SIGTERM_DRAINS, + async () => { + // Only the first node is sent SIGTERM; the peer is killed at the end. + const nodeEnv = () => ({ + WORKERD_SHUTDOWN_DELAY_MS: `${SHUTDOWN_DELAY_S * 1000}`, + }); + await withCluster( + 2, + async ({ nodes: [stopping, peer], bucket, nodeKeys }) => { + const key = nodeKeys.get(stopping.nodeId); + const first = await fetchJson( + stopping.httpPort, + '/increment?name=delayed' + ); + assert.strictEqual(first.body.nodeId, stopping.nodeId); + assert.strictEqual(await readiness(stopping.clusterPort), 200); + + const stoppedAt = Date.now(); + const exit = stopping.stop({ signal: 'SIGTERM', timeoutMs: 30_000 }); + // Not ready from the signal on, so what routes by readiness stops + // sending requests here. + assert.strictEqual(await untilNotReady(stopping.clusterPort), 503); + + // Until the delay ends, the node serves what it still gets, and its + // DO, which it still owns, runs here whichever node it is asked on. + // The node stays a member of the cluster. The requests stop 2 s + // before the delay does, so that none lands in the handoff; what + // slow CI answers only after the delay may have met the handoff, so + // only what is answered within it shows where the DO runs. + const delayEnd = stoppedAt + SHUTDOWN_DELAY_S * 1000; + let count = first.body.count; + let served = 0; + while (Date.now() < delayEnd - 2000) { + for (const node of [stopping, peer]) { + const response = await fetchJson( + node.httpPort, + '/increment?name=delayed', + { timeoutMs: 10_000 } + ); + assert.strictEqual( + response.status, + 200, + JSON.stringify(response.body) + ); + assert.strictEqual(response.body.count, ++count); + const owner = await bucket.owner(response.body.id); + if (Date.now() < delayEnd) { + assert.strictEqual(response.body.nodeId, stopping.nodeId); + assert.strictEqual(owner, key); + served++; + } + } + const members = await bucket.nodes(); + if (Date.now() < delayEnd) assert(members.includes(key)); + await sleep(200); + } + assert(served > 0, 'no request was answered within the delay'); + assert.notStrictEqual(await readiness(stopping.clusterPort), 200); + + // Then it drains as it would at once without the delay: it hands + // the DO off and leaves. + assert.deepStrictEqual(await exit, { code: 0, signal: null }); + const stopMs = Date.now() - stoppedAt; + assert(stopMs >= SHUTDOWN_DELAY_S * 1000, `stopped in ${stopMs} ms`); + assert(!(await bucket.nodes()).includes(key)); + const moved = await fetchJson(peer.httpPort, '/increment?name=delayed'); + assert.strictEqual(moved.status, 200, JSON.stringify(moved.body)); + assert.strictEqual(moved.body.nodeId, peer.nodeId); + assert.strictEqual(moved.body.count, count + 1); + }, + { nodeEnv } + ); + } +); + +test( + 'cluster: a second SIGTERM cuts the shutdown delay short', + SIGTERM_DRAINS, + async () => { + const nodeEnv = () => ({ WORKERD_SHUTDOWN_DELAY_MS: '600000' }); + await withCluster( + 1, + async ({ nodes: [node], bucket, nodeKeys }) => { + await fetchJson(node.httpPort, '/increment?name=cut-short'); + node.signal('SIGTERM'); + assert.strictEqual(await untilNotReady(node.clusterPort), 503); + // In the delay, not draining: the node is still a member well after + // a drain would have handed its one DO off and left. + await sleep(2000); + assert((await bucket.nodes()).includes(nodeKeys.get(node.nodeId))); + const response = await fetchJson( + node.httpPort, + '/increment?name=cut-short' + ); + assert.strictEqual(response.status, 200, JSON.stringify(response.body)); + + const stoppedAt = Date.now(); + const exit = await node.stop({ signal: 'SIGTERM', timeoutMs: 30_000 }); + assert.deepStrictEqual(exit, { code: 0, signal: null }); + const stopMs = Date.now() - stoppedAt; + // Within the stop timeout of 10 s, with time to exit. + assert(stopMs < 11_500, `stopped in ${stopMs} ms`); + }, + { nodeEnv } + ); + } +); + +test( + 'serve: a SIGTERM while the server starts drains it without the shutdown delay', + SIGTERM_DRAINS, + async () => { + // A worker whose evaluation keeps the server starting, synchronously, + // for seconds after it logs. + const dir = await mkdtemp(join(tmpdir(), 'workerd-starting-')); + try { + await writeFile( + join(dir, 'worker.js'), + `console.log('evaluating'); +let x = 0; +for (let j = 0; j < 8; j++) for (let i = 0; i < 1e8; i++) x = (x + i) | 0; +export default { fetch: () => new Response(String(x)) }; +` + ); + const config = join(dir, 'config.capnp'); + await writeFile( + config, + `using Workerd = import "/workerd/workerd.capnp"; +const config :Workerd.Config = ( + services = [(name = "main", worker = ( + compatibilityDate = "2024-01-01", + modules = [(name = "worker.js", esModule = embed "worker.js")], + ))], + sockets = [(name = "http", address = "127.0.0.1:0", http = (), service = "main")], +); +` + ); + const child = spawn(env.WORKERD_BINARY, ['serve', config], { + stdio: ['ignore', 'pipe', 'inherit'], + env: { ...env, WORKERD_SHUTDOWN_DELAY_MS: '600000' }, + }); + const closed = new Promise((resolve) => + child.once('close', (code, signal) => resolve({ code, signal })) + ); + const killTimer = setTimeout(() => child.kill('SIGKILL'), 60_000); + try { + // The signal handler is installed before the server starts. + let stdout = ''; + await new Promise((resolve, reject) => { + child.stdout.on('data', (chunk) => { + stdout += chunk; + if (stdout.includes('evaluating')) resolve(); + }); + closed.then(() => reject(new Error(`exited early: ${stdout}`))); + }); + child.kill('SIGTERM'); + // The server was never ready, so it drains as soon as it is up, + // rather than serve for the delay. + assert.deepStrictEqual(await closed, { code: 0, signal: null }); + } finally { + clearTimeout(killTimer); + child.kill('SIGKILL'); + } + } finally { + await rm(dir, { recursive: true, force: true }); + } + } +); + test('cluster: a freshly minted RpcTarget stub passed via props reaches its DO after it breaks', async () => { await withCluster(2, async ({ nodes }) => { const first = await fetchJson(nodes[0].httpPort, '/increment?name=root'); diff --git a/src/workerd/server/workerd.capnp b/src/workerd/server/workerd.capnp index f1ab90a4986..d95155b8ea9 100644 --- a/src/workerd/server/workerd.capnp +++ b/src/workerd/server/workerd.capnp @@ -110,6 +110,25 @@ struct Config { tracing @8 :TracingOptions; # Where the spans of Worker invocations are exported. + + shutdownDelayMs @9 :UInt32 = 0; + # How long `workerd serve` keeps serving after SIGTERM (Ctrl-Break on Windows) before it drains. + # Load balancers can go on sending new connections for a while after they learn a server is + # stopping: a cloud load balancer in front of Kubernetes, for up to about 20 seconds. Until the + # delay ends, the listeners accept and serve connections as before; then the server drains as it + # does at once with the default of 0. A second SIGTERM starts the drain at once. So does a SIGTERM + # that arrives before the server serves: it was never ready, so nothing sends it traffic. + # + # `serve`, and a binary that `workerd compile` builds, take it from the environment variable + # `WORKERD_SHUTDOWN_DELAY_MS` instead when that is set; a blank variable counts as unset. The + # variable holds a whole number of milliseconds in digits, and trailing whitespace is ignored; + # any other value ends the process at startup. So does a delay above 3600000 (an hour), from the + # variable or, when that is unset, from here. + # + # A cluster instance keeps its lease, its membership and its Durable Objects through the delay, + # while `GET /ready` on its cluster port answers 503. `ClusterConfig.stopTimeoutMs` runs from the + # end of the delay, so the supervisor's grace period (Kubernetes' `terminationGracePeriodSeconds`) + # must cover the delay plus the stop timeout. } struct ClusterConfig { @@ -293,20 +312,21 @@ struct ClusterConfig { # Tailscale uses) addresses, wildcards and hostnames are allowed. stopTimeoutMs @6 :UInt32 = 8000; - # How long an instance takes to stop, from SIGTERM to exit. Rather than leave its Durable Objects - # to wait for its lease to expire, a stopping instance hands them to its peers, busiest first, - # while it keeps serving the rest: each object takes no new requests but those that the work of - # an object being handed off makes, here or on a peer, directly or through other Durable Objects, - # its requests in flight finish, and it is released for the next request anywhere to claim. - # Requests that arrive meanwhile, other Durable Objects' calls included, wait for the object and - # then go where it runs next. While a Durable Object serves a call of a handoff's work, all the - # calls it makes count as that work. Then the instance leaves the cluster, keeps accepting - # requests until at least five seconds after SIGTERM (or until the handoff deadline, if that comes - # sooner), as load balancers take a while to stop sending them, lets its connections finish, its - # peers' last, and then stops its containers' Docker containers. Once its other connections have - # finished, it starts none of its peers' requests, and closes each peer's connection once the - # requests it started on that connection have ended, so that the peer sends those it did not - # start where their Durable Objects run next. + # How long an instance takes to stop, from SIGTERM, or from the end of its shutdown delay + # (`Config.shutdownDelayMs`), to exit. Rather than leave its Durable Objects to wait for its lease + # to expire, a stopping instance hands them to its peers, busiest first, while it keeps serving + # the rest: each object takes no new requests but those that the work of an object being handed + # off makes, here or on a peer, directly or through other Durable Objects, its requests in flight + # finish, and it is released for the next request anywhere to claim. Requests that arrive + # meanwhile, other Durable Objects' calls included, wait for the object and then go where it runs + # next. While a Durable Object serves a call of a handoff's work, all the calls it makes count as + # that work. Then the instance leaves the cluster, keeps accepting requests until at least five + # seconds after SIGTERM or the end of the shutdown delay (or until the handoff deadline, if that + # comes sooner), as load balancers take a while to stop sending them, lets its connections finish, + # its peers' last, and then stops its containers' Docker containers. Once its other connections + # have finished, it starts none of its peers' requests, and closes each peer's connection once the + # requests it started on that connection have ended, so that the peer sends those it did not start + # where their Durable Objects run next. # # The time is spent in order: until half of it, requests in flight on an object being handed off # may finish, and are then cancelled, failing as requests that may have run, which are not sent @@ -341,6 +361,18 @@ struct ClusterConfig { # # `GET /ready` on the cluster port answers 200 while the instance serves, holds its lease and is # not stopping, and 503 otherwise: a readiness probe for a rolling restart. + # + # `Config.shutdownDelayMs` puts a delay between SIGTERM and all of this, during which the instance + # serves as before and keeps its objects, but `GET /ready` answers 503: for load balancers that go + # on sending requests for a while, as a cloud load balancer in front of Kubernetes does. The + # supervisor's grace period must then cover the delay plus this timeout. + # + # `serve`, and a binary that `workerd compile` builds, take this from the environment variable + # `WORKERD_CLUSTER_STOP_TIMEOUT_MS` instead when that is set, as they take + # `Config.shutdownDelayMs` from `WORKERD_SHUTDOWN_DELAY_MS`, so the two timings that the grace + # period must cover are set in one place. A blank variable counts as unset. It holds a whole + # number of milliseconds in digits, and trailing whitespace is ignored; any other value, or one + # above 3600000 (an hour), ends the process at startup. unsafeTimeDivisor @7 :UInt32 = 1; # For tests: divides by this the times that a takeover and a stop wait out, which tests would