diff --git a/.github/workflows/docker.yml b/.github/workflows/docker.yml index 66de96d9..20b47743 100644 --- a/.github/workflows/docker.yml +++ b/.github/workflows/docker.yml @@ -56,4 +56,24 @@ jobs: docker volume create space-ci > /dev/null id=$(echo 'hello from the image' | docker run --rm -i -v space-ci:/data space-core:ci create -q -) docker run --rm -v space-ci:/data space-core:ci read "$id" | grep -qx 'hello from the image' + + # As PID 1, serve-s3 must handle docker stop's SIGTERM itself: stop well + # inside the 10 s timeout, with exit status 0, not a SIGKILL. + - name: docker stop + run: | + docker run -d --name space-stop -v space-ci:/data space-core:ci serve-s3 > /dev/null + for _ in $(seq 60); do + docker logs space-stop 2>&1 | grep -q ' listening ' && break + sleep 1 + done + docker logs space-stop 2>&1 | grep -q ' listening ' \ + || { docker logs space-stop; echo "::error::serve-s3 didn't start"; exit 1; } + start=$(date +%s) + docker stop space-stop > /dev/null + took=$(( $(date +%s) - start )) + status=$(docker inspect --format '{{.State.ExitCode}}' space-stop) + docker logs space-stop 2>&1 | tail -n 3 + docker rm space-stop > /dev/null docker volume rm space-ci > /dev/null + [ "$status" = 0 ] || { echo "::error::serve-s3 exited with $status after docker stop"; exit 1; } + [ "$took" -lt 8 ] || { echo "::error::docker stop took ${took}s"; exit 1; } diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index beae3e37..89418828 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -32,6 +32,8 @@ The data log and the journal are the truth; `space.db` can be rebuilt from them. - **Reclaim** (`--reclaim-interval`; `spacectl gc` and `spacectl compact`): `serve-s3`'s pass first aborts multipart uploads started more than 7 days ago. It compacts `space.nvram` into its next generation once enough of it is unreferenced, or deletes unreferenced segment files under `SPACE_STORAGE_ROOT`. Then it compacts `space.journal` once enough of it is dead: deleted and overwritten capsules, and removed S3 keys. See [capsule.md §7](docs/capsule.md#7-deletion-ref-counting-and-gc). - **Scrub** (`--scrub-interval` and `--deep-scrub-interval`; `spacectl scrub`): light scrub checks each record's checksums, and deep scrub checks MACs and content hashes, then reads capsules whole to check their digests. See [capsule.md §8](docs/capsule.md#8-scrub-continuous-integrity). +On SIGTERM or Ctrl-C, `serve-s3` stops accepting connections and gives the requests in flight `--shutdown-grace` seconds (default 5) to finish. Requests still running then get a 503, which S3 clients retry. Then it stops both loops and exits. A compaction still running is abandoned, as a crash would leave it, and the next open discards the unfinished generation. + ## Status Single-node only. Property tests cover the main pipeline invariants. See [RESET.md](RESET.md) and [README.md](README.md). diff --git a/CHANGELOG.md b/CHANGELOG.md index f725910d..5b842c68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- `serve-s3` shuts down cleanly on SIGTERM or Ctrl-C (and on Windows Ctrl-Break, the console closing or the system shutting down). It stops accepting connections, closes idle ones, and gives the requests in flight `--shutdown-grace` seconds (default 5, inside `docker stop`'s 10) to finish. Any still running then get `503 ServiceUnavailable`, which S3 clients retry. It then stops reclaim and scrub, logs `stopped` and exits 0, waiting at most 2 s for a compaction still running on a blocking thread. That compaction is abandoned as after a crash, so a large store can't hold the exit past `docker stop`'s timeout. A second signal exits at once. It used to have no signal handling, so as PID 1 in a container it ignored `docker stop` until it was killed after the timeout. `S3Server::shutdown_on` does the same for code that embeds the server. - The S3 view does multipart upload (#201): CreateMultipartUpload, UploadPart, ListParts, CompleteMultipartUpload and AbortMultipartUpload. SDK uploads over their multipart threshold, such as boto3's `upload_file` above 8 MiB, used to get `501 NotImplemented`. Each part is checked against its digest headers and trailer as a PUT body is. Every part but the last must be at least 5 MiB. Completing reads the parts once for the object's digest, and makes the object of the parts' segments without writing them again, in one journal `BATCH` that also drops the parts and any object the key held. An open upload is a namespace in the journal (on-disk format §5.6, §6), so it survives a restart and an index rebuild. `serve-s3`'s reclaim pass aborts uploads started more than 7 days ago. The object's ETag is its capsule id, as a PUT's is. ListMultipartUploads and UploadPartCopy get `501 NotImplemented`. - `spacectl` works in scripts (#169). `create` takes the file as an argument, or reads stdin for `-` or when stdin is a pipe, and `-q` prints only the capsule ID. `-f FILE` still works. `read -o FILE` writes the capsule to a file, removed again if the read fails part way, and `read` won't write a capsule that looks binary to a terminal without `--force`. `list --json` prints one object per capsule per line, with its ID, size, segments, creation time, whether it's encrypted and the names bound to it. `list` prints a fixed-width table, oldest first, with a Created column, where it used tabs in ID order. `spacectl completions ` prints a completion script, using the new `clap_complete` dependency. - A deep scrub checks each capsule against its digest after its segments (#140). It reads the capsule whole and reports `CapsuleCorrupted`, naming it, when the bytes don't match: for example a manifest whose segments are each sound but listed in the wrong order, which used to pass every scrub. In the background, a deep cycle checks the capsules that hold a segment it just scrubbed, so a restart doesn't read the whole store again. `spacectl scrub --deep` checks every capsule and prints how many it checked. Capsules without a digest, and encrypted ones without the key, are skipped and counted. @@ -51,7 +52,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Issues: #103, #104, #105, #110. - Dependabot labels its PRs `dependencies`, a label the repo now has, and no longer labels every cargo bump `security` (#203). That label is now added by hand to PRs that fix an advisory. - `KeyManager` no longer has `rotate()`, `complete_rotation()` or `is_rotating()`, and `Keyring` no longer has `rotate_key()` (#98). The rotation only changed the key version in memory, so a restart sent new writes back to version 1, and nothing in `spacectl` or `serve-s3` called it. A new version also protected nothing: every version derives from the same master key, and dedup kept new writes on segments under the old version. New writes use version 1, and segments of any version stay readable. The encryption docs and SECURITY.md say so. -- CI runs the tests on Windows and macOS as well as Linux, and adds rustdoc with warnings denied, spell checking (`typos`), workflow linting (`actionlint`, `zizmor`), dependency review on pull requests, `--locked` on every cargo command, and a weekly run for new advisories and lints. The required `Build and test` check now passes only when every CI job passes, and runs on Markdown-only pull requests too, which could never be merged before. New workflows run CodeQL, OpenSSF Scorecard, a Docker image build with a smoke test, a link check and a path labeler. Every action is pinned to a commit and jobs get a read-only token unless they need more. Releases build `spacectl` for Linux (x86_64, aarch64), Windows and macOS after the whole CI suite passes, with `SHA256SUMS` and build provenance attestations. Dependabot also updates the Docker base images, waits seven days before proposing a new version, and groups action bumps into one PR. The Docker image builds on current stable Rust and runs as a non-root user that can write its `/data` store, from base images pinned by digest; its header says to run it with `--init`, since `spacectl` doesn't handle signals as PID 1. The repo has `.gitattributes` (LF line endings everywhere), `.editorconfig`, `.dockerignore`, `SUPPORT.md` and `CITATION.cff`, and no longer tracks `crates/protocol-s3/space.kyber.key`, a key pair left by a pre-reset build. See docs/CI_CD_STRATEGY.md. +- CI runs the tests on Windows and macOS as well as Linux, and adds rustdoc with warnings denied, spell checking (`typos`), workflow linting (`actionlint`, `zizmor`), dependency review on pull requests, `--locked` on every cargo command, and a weekly run for new advisories and lints. The required `Build and test` check now passes only when every CI job passes, and runs on Markdown-only pull requests too, which could never be merged before. New workflows run CodeQL, OpenSSF Scorecard, a Docker image build with a smoke test, a link check and a path labeler. Every action is pinned to a commit and jobs get a read-only token unless they need more. Releases build `spacectl` for Linux (x86_64, aarch64), Windows and macOS after the whole CI suite passes, with `SHA256SUMS` and build provenance attestations. Dependabot also updates the Docker base images, waits seven days before proposing a new version, and groups action bumps into one PR. The Docker image builds on current stable Rust and runs as a non-root user that can write its `/data` store, from base images pinned by digest. The repo has `.gitattributes` (LF line endings everywhere), `.editorconfig`, `.dockerignore`, `SUPPORT.md` and `CITATION.cff`, and no longer tracks `crates/protocol-s3/space.kyber.key`, a key pair left by a pre-reset build. See docs/CI_CD_STRATEGY.md. - `docs/capsule.md`, ARCHITECTURE.md, README.md and ROADMAP.md describe what landed with #169, #188, #198 and #201: where the write path takes the pipeline lock, how the content index is kept, multipart upload namespaces and composed capsules, the reclaim pass aborting old uploads, and `spacectl`'s scripting flags and completions. ### Fixed diff --git a/Dockerfile b/Dockerfile index a4694b2d..39d172c7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -3,10 +3,10 @@ # docker run --rm space-core:latest --help # # Stores live in /data, the working directory. Mount a volume there to keep -# them, and bind beyond the container's loopback to reach serve-s3. Pass -# --init so that docker stop and Ctrl-C reach spacectl, which doesn't handle -# signals itself and would otherwise be killed after the stop timeout: -# docker run --rm --init -v space-data:/data -p 8080:8080 space-core:latest serve-s3 --bind 0.0.0.0 +# them, and bind beyond the container's loopback to reach serve-s3: +# docker run --rm -v space-data:/data -p 8080:8080 space-core:latest serve-s3 --bind 0.0.0.0 +# docker stop lets requests in flight finish for --shutdown-grace seconds +# (default 5) before serve-s3 exits. # # The image runs as uid 10001. To bind-mount a host directory instead of a # volume, make it writable by that uid or run with --user "$(id -u):$(id -g)". diff --git a/crates/protocol-s3/src/handlers.rs b/crates/protocol-s3/src/handlers.rs index 9174b94e..2d55a377 100644 --- a/crates/protocol-s3/src/handlers.rs +++ b/crates/protocol-s3/src/handlers.rs @@ -71,6 +71,9 @@ impl IntoResponse for S3Error { ); return (StatusCode::NOT_MODIFIED, headers).into_response(); } + S3Error::ServiceUnavailable => { + (StatusCode::SERVICE_UNAVAILABLE, "ServiceUnavailable", "") + } S3Error::Internal(err) => { error!("request failed: {err:#}"); (StatusCode::INTERNAL_SERVER_ERROR, "InternalError", "") diff --git a/crates/protocol-s3/src/lib.rs b/crates/protocol-s3/src/lib.rs index 50ae7044..ad41bb49 100644 --- a/crates/protocol-s3/src/lib.rs +++ b/crates/protocol-s3/src/lib.rs @@ -123,6 +123,10 @@ pub enum S3Error { /// 304 carrying the object's validators. #[error("Not Modified")] NotModified(Box), + /// A request the server cut off because it was shutting down and the + /// grace period ran out. S3 clients retry a 503. + #[error("The server is shutting down. Please retry the request.")] + ServiceUnavailable, #[error(transparent)] Internal(#[from] anyhow::Error), } diff --git a/crates/protocol-s3/src/server.rs b/crates/protocol-s3/src/server.rs index 6b3536c8..1a3e4b61 100644 --- a/crates/protocol-s3/src/server.rs +++ b/crates/protocol-s3/src/server.rs @@ -9,13 +9,15 @@ use axum::{ Router, }; -use std::future::IntoFuture; +use std::future::{Future, IntoFuture}; use std::net::{Ipv4Addr, Ipv6Addr}; use std::sync::Arc; use std::time::Duration; +use futures::future::{BoxFuture, FutureExt}; use tokio::net::TcpListener; use tokio::task::JoinHandle; +use tokio_util::sync::CancellationToken; use tower_http::trace::TraceLayer; use tracing::{debug, info, warn}; @@ -184,6 +186,7 @@ pub struct S3Server { reclaim_every: Option, scrub: Option, hosts: AllowedHosts, + shutdown: Option<(BoxFuture<'static, ()>, Duration)>, } impl S3Server { @@ -196,9 +199,24 @@ impl S3Server { reclaim_every: None, scrub: None, hosts: AllowedHosts::default(), + shutdown: None, } } + /// Stop when `signal` completes: stop accepting connections, close idle + /// keep-alive ones, and let the requests in flight finish for up to + /// `grace`. Requests still running then are cut off with a 503, which S3 + /// clients retry, and `run` returns. Without this, the default, the + /// server runs until it fails or the process is killed. + pub fn shutdown_on( + mut self, + signal: impl Future + Send + 'static, + grace: Duration, + ) -> Self { + self.shutdown = Some((Box::pin(signal), grace)); + self + } + /// The hosts requests may name ([`AllowedHosts`]). The default is /// `localhost` and IP addresses. pub fn allow_hosts(mut self, hosts: AllowedHosts) -> Self { @@ -220,6 +238,10 @@ impl S3Server { self } + /// Serve until a listener fails or, with [`shutdown_on`](Self::shutdown_on), + /// until the shutdown signal. The background reclaim and scrub tasks stop + /// when this returns. Like a crash, stopping one part way leaves nothing + /// a later open has to repair by hand. pub async fn run(self) -> Result<()> { let _reclaim = self .reclaim_every @@ -236,17 +258,75 @@ impl S3Server { "try: curl -X PUT http://{addr}/demo-bucket && curl -X PUT http://{addr}/demo-bucket/hello.txt --data-binary 'Hello SPACE!'" ); } - let servers = self - .listeners - .into_iter() - .map(|listener| axum::serve(listener, app.clone()).into_future()); - futures::future::try_join_all(servers).await?; + let Some((signal, grace)) = self.shutdown else { + let servers = self + .listeners + .into_iter() + .map(|listener| axum::serve(listener, app.clone()).into_future()); + futures::future::try_join_all(servers).await?; + return Ok(()); + }; + + // Every listener stops on the one signal. + let signal = signal.shared(); + let cut_off = CancellationToken::new(); + let app = app.layer(middleware::from_fn_with_state( + cut_off.clone(), + cut_off_when_told, + )); + let servers = self.listeners.into_iter().map(|listener| { + axum::serve(listener, app.clone()) + .with_graceful_shutdown(signal.clone()) + .into_future() + }); + let draining = futures::future::try_join_all(servers); + tokio::pin!(draining); + let deadline = async { + signal.clone().await; + tokio::time::sleep(grace).await; + }; + tokio::select! { + served = &mut draining => { + served?; + return Ok(()); + } + () = deadline => {} + } + warn!("cutting off the requests still in flight {grace:?} after the shutdown signal"); + cut_off.cancel(); + // A connection closes once its handler has answered. One with + // nothing to cancel, such as a response body still streaming, closes + // when the runtime shuts down. + if tokio::time::timeout(WIND_DOWN, &mut draining) + .await + .is_err() + { + warn!("some connections were still open after the cut-off"); + } Ok(()) } } -/// Stops the reclaim task when the server stops. +/// How long [`S3Server::run`] waits for connections to close after cutting +/// off their requests. +const WIND_DOWN: Duration = Duration::from_secs(1); + +/// Drops a request's handler, and answers 503 ServiceUnavailable, once the +/// server cuts off what's still in flight after a shutdown signal. S3 +/// clients retry a 503, so the request can go to the next server. +async fn cut_off_when_told( + State(cut_off): State, + request: Request, + next: Next, +) -> Response { + tokio::select! { + response = next.run(request) => response, + () = cut_off.cancelled() => S3Error::ServiceUnavailable.into_response(), + } +} + +/// Stops a background task when the server stops. struct AbortOnDrop(JoinHandle<()>); impl Drop for AbortOnDrop { diff --git a/crates/protocol-s3/tests/shutdown_test.rs b/crates/protocol-s3/tests/shutdown_test.rs new file mode 100644 index 00000000..02286cce --- /dev/null +++ b/crates/protocol-s3/tests/shutdown_test.rs @@ -0,0 +1,172 @@ +//! `S3Server::shutdown_on`: what a server does between its shutdown signal +//! and returning, over real sockets. + +use capsule_registry::modular_pipeline::StoreSecurity; +use capsule_registry::CapsuleRegistry; +use nvram_sim::NvramLog; +use protocol_s3::{server::S3Server, S3View}; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; +use tokio::sync::oneshot; +use tokio::task::JoinHandle; +use tokio::time::timeout; + +/// Far longer than any of this should take, so a slow CI machine doesn't +/// fail a test, while a server that never stops still does. +const PATIENCE: Duration = Duration::from_secs(20); + +struct Running { + dir: PathBuf, + addr: SocketAddr, + stop: Option>, + server: JoinHandle>, +} + +impl Running { + async fn start(name: &str, grace: Duration) -> Self { + let dir = std::env::temp_dir().join(format!("s3_shutdown_{name}_{}", uuid::Uuid::new_v4())); + std::fs::create_dir_all(&dir).unwrap(); + let view = open_view(&dir); + view.create_bucket("demo").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = listener.local_addr().unwrap(); + let (stop, stopped) = oneshot::channel::<()>(); + let server = S3Server::new(view, vec![listener]).shutdown_on( + async move { + let _ = stopped.await; + }, + grace, + ); + Self { + dir, + addr, + stop: Some(stop), + server: tokio::spawn(server.run()), + } + } + + fn signal(&mut self) { + self.stop.take().unwrap().send(()).unwrap(); + } + + /// Waits for the server to return, and says how long it took. + async fn stopped(self) -> (PathBuf, Duration) { + let started = Instant::now(); + timeout(PATIENCE, self.server) + .await + .expect("the server didn't stop") + .expect("the server task panicked") + .expect("the server failed"); + (self.dir, started.elapsed()) + } +} + +fn open_view(dir: &Path) -> S3View { + let registry = CapsuleRegistry::open(dir.join("space.db")).unwrap(); + let log = NvramLog::open(dir.join("space.nvram")).unwrap(); + S3View::new(registry, log, &StoreSecurity::none()).unwrap() +} + +/// Reads one response's head off a connection that stays open. +async fn read_head(stream: &mut TcpStream) -> String { + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + let n = timeout(PATIENCE, stream.read(&mut byte)) + .await + .expect("no response") + .unwrap(); + assert_eq!(n, 1, "connection closed mid-response: {head:?}"); + head.push(byte[0]); + } + String::from_utf8(head).unwrap() +} + +#[tokio::test] +async fn an_idle_connection_is_closed_and_doesnt_hold_up_the_stop() { + let mut running = Running::start("idle", PATIENCE).await; + let mut idle = TcpStream::connect(running.addr).await.unwrap(); + idle.write_all(b"GET /-/health HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n") + .await + .unwrap(); + let head = read_head(&mut idle).await; + assert!(head.starts_with("HTTP/1.1 200"), "{head}"); + // Drain the small body, leaving a keep-alive connection with nothing in + // flight. + tokio::time::sleep(Duration::from_millis(100)).await; + let mut body = [0u8; 256]; + let _ = timeout(Duration::from_millis(500), idle.read(&mut body)).await; + + running.signal(); + let addr = running.addr; + let (_, took) = running.stopped().await; + assert!( + took < PATIENCE / 2, + "waited on an idle connection: {took:?}" + ); + + let mut rest = Vec::new(); + let closed = timeout(PATIENCE, idle.read_to_end(&mut rest)).await; + assert!( + matches!(closed, Ok(Ok(_)) | Ok(Err(_))), + "the idle connection was left open" + ); + // Nothing listens any more. + assert!( + !matches!(timeout(PATIENCE, TcpStream::connect(addr)).await, Ok(Ok(_))), + "still accepting connections after stopping" + ); +} + +#[tokio::test] +async fn a_request_in_flight_at_the_signal_finishes() { + let mut running = Running::start("in_flight", PATIENCE).await; + let mut put = TcpStream::connect(running.addr).await.unwrap(); + put.write_all(b"PUT /demo/k HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 10\r\n\r\nhello") + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + + running.signal(); + tokio::time::sleep(Duration::from_millis(200)).await; + put.write_all(b"world").await.unwrap(); + let head = read_head(&mut put).await; + assert!(head.starts_with("HTTP/1.1 200"), "{head}"); + + let (dir, _) = running.stopped().await; + // The server let go of the store, and the PUT is in it. + let view = open_view(&dir); + assert_eq!(view.head_object("demo", "k").unwrap().size(), 10); +} + +#[tokio::test] +async fn a_request_still_running_after_the_grace_period_is_cut_off() { + let grace = Duration::from_millis(300); + let mut running = Running::start("cut_off", grace).await; + let mut put = TcpStream::connect(running.addr).await.unwrap(); + // A body that never arrives in full. + put.write_all(b"PUT /demo/k HTTP/1.1\r\nHost: 127.0.0.1\r\nContent-Length: 10\r\n\r\nhello") + .await + .unwrap(); + tokio::time::sleep(Duration::from_millis(200)).await; + + running.signal(); + // Cut off with a 503, which S3 clients retry. + let head = read_head(&mut put).await; + assert!(head.starts_with("HTTP/1.1 503"), "{head}"); + let (dir, took) = running.stopped().await; + assert!( + took < PATIENCE / 2, + "didn't stop after the grace period: {took:?}" + ); + + // The server let go of the store, and nothing of the PUT is in it. + let view = open_view(&dir); + assert!( + view.head_object("demo", "k").is_err(), + "half a PUT was stored" + ); +} diff --git a/crates/spacectl/src/main.rs b/crates/spacectl/src/main.rs index 3ba1ce48..946bfc51 100644 --- a/crates/spacectl/src/main.rs +++ b/crates/spacectl/src/main.rs @@ -432,6 +432,12 @@ enum Commands { /// them off. #[arg(long, default_value_t = 300, value_name = "SECONDS")] reclaim_interval: u64, + /// Seconds to let requests in flight finish after SIGTERM or Ctrl-C + /// before stopping anyway. New connections are refused at once, and a + /// second signal stops the server without waiting. The default leaves + /// time inside docker stop's 10 s. + #[arg(long, default_value_t = 5, value_name = "SECONDS")] + shutdown_grace: u64, #[command(flatten)] scrub: ScrubArgs, }, @@ -616,6 +622,90 @@ fn log_startup( } } +/// The signals that stop serve-s3: SIGTERM and SIGINT (Ctrl-C), or on +/// Windows Ctrl-C, Ctrl-Break and the console closing or the system shutting +/// down. They're registered before the server starts, so a failure to listen +/// for them is a startup error rather than a server that can't be stopped. +/// Once registered, they no longer kill the process on their own, which +/// matters most for PID 1 in a container: there the kernel ignores a signal +/// with no handler, so `docker stop` used to wait out its timeout. +struct StopSignals { + #[cfg(unix)] + terminate: tokio::signal::unix::Signal, + #[cfg(unix)] + interrupt: tokio::signal::unix::Signal, + #[cfg(windows)] + ctrl_c: tokio::signal::windows::CtrlC, + #[cfg(windows)] + ctrl_break: tokio::signal::windows::CtrlBreak, + #[cfg(windows)] + ctrl_close: tokio::signal::windows::CtrlClose, + #[cfg(windows)] + ctrl_shutdown: tokio::signal::windows::CtrlShutdown, +} + +impl StopSignals { + fn register() -> io::Result { + #[cfg(unix)] + { + use tokio::signal::unix::{signal, SignalKind}; + Ok(Self { + terminate: signal(SignalKind::terminate())?, + interrupt: signal(SignalKind::interrupt())?, + }) + } + #[cfg(windows)] + { + use tokio::signal::windows; + Ok(Self { + ctrl_c: windows::ctrl_c()?, + ctrl_break: windows::ctrl_break()?, + ctrl_close: windows::ctrl_close()?, + ctrl_shutdown: windows::ctrl_shutdown()?, + }) + } + } + + /// Waits for the next stop signal and names it. + async fn next(&mut self) -> &'static str { + #[cfg(unix)] + { + tokio::select! { + _ = self.terminate.recv() => "SIGTERM", + _ = self.interrupt.recv() => "SIGINT", + } + } + #[cfg(windows)] + { + tokio::select! { + _ = self.ctrl_c.recv() => "Ctrl-C", + _ = self.ctrl_break.recv() => "Ctrl-Break", + _ = self.ctrl_close.recv() => "console closed", + _ = self.ctrl_shutdown.recv() => "system shutdown", + } + } + } + + /// Resolves on the first stop signal. A second one exits the process at + /// once, for when the requests in flight aren't worth waiting for. + async fn first_then_force(mut self, grace: Duration) { + let signal = self.next().await; + info!( + signal, + grace_secs = grace.as_secs(), + "shutting down: finishing requests in flight; signal again to stop now" + ); + tokio::spawn(async move { + let signal = self.next().await; + warn!( + signal, + "stopping now, without waiting for requests in flight" + ); + std::process::exit(130); + }); + } +} + /// A policy file's settings over `base`. Unknown keys and settings nothing /// implements are errors (#161, #162). fn load_policy_file(path: &PathBuf, base: Policy) -> Result { @@ -624,16 +714,28 @@ fn load_policy_file(path: &PathBuf, base: Policy) -> Result { Ok(file.apply(base)?) } -#[tokio::main] -async fn main() -> Result<()> { - let cli = Cli::parse(); - let default_level = match cli.command { - Commands::ServeS3 { .. } => "info", - _ => "warn", - }; - init_tracing(default_level); +/// How long `spacectl` waits at exit for blocking work a command left +/// running. Only `serve-s3` leaves any: a reclaim pass compacts on a +/// blocking thread, which stopping the server can't cancel. Dropping the +/// runtime would wait for it however long it takes, past `docker stop`'s +/// timeout on a large store. Abandoning it is safe: compaction writes the +/// next generation beside the live file and renames it in, and the next +/// open discards a generation it didn't finish, as after a crash. +const EXIT_WAIT: Duration = Duration::from_secs(2); - match run(cli).await { +fn main() -> Result<()> { + let runtime = tokio::runtime::Runtime::new().context("couldn't start the async runtime")?; + let result = runtime.block_on(async { + let cli = Cli::parse(); + let default_level = match cli.command { + Commands::ServeS3 { .. } => "info", + _ => "warn", + }; + init_tracing(default_level); + run(cli).await + }); + runtime.shutdown_timeout(EXIT_WAIT); + match result { // A reader that stopped early, such as `head`, isn't a failure. Err(err) if broken_pipe(&err) => Ok(()), result => result, @@ -890,6 +992,7 @@ async fn run(cli: Cli) -> Result<()> { bind, allow_host, reclaim_interval, + shutdown_grace, scrub, } => { use protocol_s3::{ @@ -912,11 +1015,16 @@ async fn run(cli: Cli) -> Result<()> { let s3_view = S3View::new_modular(store); let reclaim_every = (reclaim_interval > 0).then(|| Duration::from_secs(reclaim_interval)); + let grace = Duration::from_secs(shutdown_grace); + let signals = StopSignals::register() + .context("couldn't listen for the signals that stop the server")?; let server = S3Server::new(s3_view, listeners) .allow_hosts(AllowedHosts::with_names(allow_host)) .reclaim_every(reclaim_every) - .scrub(scrub.config()); + .scrub(scrub.config()) + .shutdown_on(signals.first_then_force(grace), grace); server.run().await?; + info!("stopped"); } } @@ -1031,6 +1139,12 @@ mod tests { assert_eq!(bind, None, "both loopback addresses"); assert_eq!(reclaim_interval, 300); + let cli = Cli::try_parse_from(["spacectl", "serve-s3"]).unwrap(); + let Commands::ServeS3 { shutdown_grace, .. } = cli.command else { + panic!("expected serve-s3"); + }; + assert_eq!(shutdown_grace, 5, "inside docker stop's 10 s"); + let cli = Cli::try_parse_from(["spacectl", "serve-s3", "--reclaim-interval", "0"]).unwrap(); let Commands::ServeS3 { reclaim_interval, .. diff --git a/crates/spacectl/tests/cli_test.rs b/crates/spacectl/tests/cli_test.rs index 306a591f..99f6e143 100644 --- a/crates/spacectl/tests/cli_test.rs +++ b/crates/spacectl/tests/cli_test.rs @@ -880,6 +880,68 @@ fn serve_s3_reports_and_serves_every_address_it_listens_on() { let _ = std::fs::remove_dir_all(&dir); } +/// SIGTERM, as `docker stop` sends it, stops `serve-s3` cleanly: it logs the +/// shutdown, exits 0 well within docker's 10 s, and leaves a store the next +/// command opens. Unix only: a test can't send a child Ctrl-C on Windows. +#[cfg(unix)] +#[test] +fn serve_s3_stops_cleanly_on_sigterm() { + use std::io::{BufRead, BufReader}; + + let dir = scratch_dir("serve_sigterm"); + let mut child = spawn( + &dir, + &["serve-s3", "--port", "0"], + &[("RUST_LOG", Path::new("info"))], + ); + let stderr = child.stderr.take().unwrap(); + let (lines, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + for line in BufReader::new(stderr).lines().map_while(Result::ok) { + if lines.send(line).is_err() { + break; + } + } + }); + let mut seen = Vec::new(); + loop { + match rx.recv_timeout(Duration::from_secs(60)) { + Ok(line) if line.contains(" listening ") => break, + Ok(line) => seen.push(line), + Err(err) => { + let _ = child.kill(); + panic!("no listening line ({err}): {seen:?}"); + } + } + } + + let sent = Instant::now(); + let kill = Command::new("kill") + .args(["-TERM", &child.id().to_string()]) + .status() + .unwrap(); + assert!(kill.success()); + let out = exit_of(child, "serve-s3 ignored SIGTERM"); + let took = sent.elapsed(); + // The reader thread ends at the end of stderr, once the process exits. + while let Ok(line) = rx.recv_timeout(Duration::from_secs(10)) { + seen.push(line); + } + assert!(out.status.success(), "{:?}: {seen:?}", out.status); + assert!(took < Duration::from_secs(8), "took {took:?} to stop"); + assert!( + seen.iter() + .any(|line| line.contains("shutting down") && line.contains("SIGTERM")), + "{seen:?}" + ); + assert!(seen.iter().any(|line| line.contains("stopped")), "{seen:?}"); + + // The store it served opens again. + let list = spacectl(&dir, &["list"]); + assert!(list.status.success(), "{list:?}"); + let _ = std::fs::remove_dir_all(&dir); +} + /// A store whose space.journal is missing isn't opened, so nothing reclaims /// its segments: not `compact`, and not the pass `serve-s3` runs at startup /// (#194). diff --git a/docs/CI_CD_STRATEGY.md b/docs/CI_CD_STRATEGY.md index 85be2f37..fcca2972 100644 --- a/docs/CI_CD_STRATEGY.md +++ b/docs/CI_CD_STRATEGY.md @@ -9,7 +9,7 @@ Everything runs on GitHub Actions. Every action is pinned to a full commit SHA, | [`ci.yml`](../.github/workflows/ci.yml) | pull requests, pushes to `main`, merge queue, weekly, manual, and from `release.yml` | fmt, clippy (also with `storage/uring`), tests on Linux, Windows and macOS, `cargo check` of the libraries and binaries on `rust-version`, rustdoc with warnings denied, `cargo audit`, `cargo deny`, dependency review (pull requests only), `typos`, `actionlint` and `zizmor`, plus a check that the license field is `BUSL-1.1` | yes, through the `Build and test` job | | [`codeql.yml`](../.github/workflows/codeql.yml) | pull requests, pushes to `main`, weekly | CodeQL analysis of the Rust code and of the workflows; results go to code scanning | no | | [`scorecard.yml`](../.github/workflows/scorecard.yml) | pushes to `main`, weekly, branch protection changes | OpenSSF Scorecard; publishes the score shown in the README and uploads findings to code scanning | no | -| [`docker.yml`](../.github/workflows/docker.yml) | changes to the Dockerfile, `.dockerignore`, `Cargo.toml` or `Cargo.lock`; weekly | hadolint, `docker build` (on current stable Rust, from digest-pinned base images), and a smoke test that writes and reads a capsule as the image's non-root user | no | +| [`docker.yml`](../.github/workflows/docker.yml) | changes to the Dockerfile, `.dockerignore`, `Cargo.toml` or `Cargo.lock`; weekly | hadolint, `docker build` (on current stable Rust, from digest-pinned base images), a smoke test that writes and reads a capsule as the image's non-root user, and a check that `docker stop` ends `serve-s3` with exit status 0 well inside its timeout | no | | [`links.yml`](../.github/workflows/links.yml) | changes to Markdown, weekly | lychee over every Markdown file (ignores in `.lycheeignore`) | no, an outside site being down shouldn't block a merge | | [`labeler.yml`](../.github/workflows/labeler.yml) | pull requests from this repository | labels the pull request by the paths it changes ([`.github/labeler.yml`](../.github/labeler.yml)) | no | | [`release.yml`](../.github/workflows/release.yml) | `v*` tags; pull requests that change it (build only) | see below | no | diff --git a/docs/capsule.md b/docs/capsule.md index 281471ee..94cdeff4 100644 --- a/docs/capsule.md +++ b/docs/capsule.md @@ -498,7 +498,7 @@ Segments still referenced by other Capsules remain. `spacectl delete` removes an **Bytes remain in the log** until compaction (`NvramLog::compact()`) writes the next generation without them. The two-step design keeps deletion cheap (touch one record) and bulk reclamation infrequent. In the NVRAM log, compaction alone reclaims unreferenced segments, since they have no references in the log's counts. Under `SPACE_STORAGE_ROOT` each segment is a file, and garbage collection deletes it. -**Scheduling.** `serve-s3` runs a reclaim pass at startup and then every `--reclaim-interval` seconds (default 300; 0 turns it off): +**Scheduling.** `serve-s3` runs a reclaim pass at startup and then every `--reclaim-interval` seconds (default 300; 0 turns it off). Stopping the server abandons a pass part way, as a crash would. The next open discards an unfinished compaction, so nothing needs repairing by hand: - On the NVRAM log it compacts once a quarter of the log, and at least one default segment (4 MiB), is reclaimable, on a blocking thread and without the pipeline lock, so requests carry on. - Under `SPACE_STORAGE_ROOT` it garbage-collects, with the pipeline lock held. diff --git a/docs/guides/QUICKSTART_S3.md b/docs/guides/QUICKSTART_S3.md index de76ef81..a9867bc4 100644 --- a/docs/guides/QUICKSTART_S3.md +++ b/docs/guides/QUICKSTART_S3.md @@ -49,6 +49,8 @@ While it runs, the server reclaims the space of deleted objects and interrupted It also scrubs the store, reading at most 64 MiB/s (`--scrub-rate`): each segment gets a deep scrub weekly (`--deep-scrub-interval`) and a light scrub daily (`--scrub-interval`, `0` to turn scrubbing off). When each segment was last checked is kept in `space.db`, so a restart only scrubs segments that are new or due. Damage is logged at `WARN`, and it's kept in `space.db` too, so it's reported every cycle and after a restart until a scrub passes the segment ([#195](https://github.com/saworbit/SPACE/issues/195)). A deep scrub also reads capsules whole and checks each against its digest ([#140](https://github.com/saworbit/SPACE/issues/140)). With the server stopped, `spacectl scrub --deep` lists any damaged segments and the capsules that hold them, and any capsule that doesn't read back as its digest. +Stop the server with Ctrl-C, or SIGTERM, which is what `docker stop` sends. It stops taking new connections and gives the requests in flight 5 seconds (`--shutdown-grace`) to finish. Any still running after that get `503 ServiceUnavailable`, which S3 clients retry. It logs `stopped` and exits 0. A second Ctrl-C stops it at once. + ## 2. PUT an object Create a bucket, then PUT an object into it: @@ -116,7 +118,7 @@ Use `--data-binary`. Plain `-d` strips newlines. ## 6. Read the same capsule through spacectl -The S3 view and `spacectl` share one capsule store. Stop the server first: sled allows only one process to open `space.db`, so `spacectl` can't run alongside `serve-s3` ([#92](https://github.com/saworbit/SPACE/issues/92)). Then read the capsule by the ETag from step 2: +The S3 view and `spacectl` share one capsule store. Stop the server first (Ctrl-C): sled allows only one process to open `space.db`, so `spacectl` can't run alongside `serve-s3` ([#92](https://github.com/saworbit/SPACE/issues/92)). Then read the capsule by the ETag from step 2: ```bash ./target/release/spacectl list