Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions .github/workflows/docker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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; }
2 changes: 2 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <shell>` 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.
Expand Down Expand Up @@ -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
Expand Down
8 changes: 4 additions & 4 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -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)".
Expand Down
3 changes: 3 additions & 0 deletions crates/protocol-s3/src/handlers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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", "")
Expand Down
4 changes: 4 additions & 0 deletions crates/protocol-s3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,10 @@ pub enum S3Error {
/// 304 carrying the object's validators.
#[error("Not Modified")]
NotModified(Box<ObjectMapping>),
/// 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),
}
Expand Down
94 changes: 87 additions & 7 deletions crates/protocol-s3/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};

Expand Down Expand Up @@ -184,6 +186,7 @@ pub struct S3Server {
reclaim_every: Option<Duration>,
scrub: Option<ScrubConfig>,
hosts: AllowedHosts,
shutdown: Option<(BoxFuture<'static, ()>, Duration)>,
}

impl S3Server {
Expand All @@ -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<Output = ()> + 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 {
Expand All @@ -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
Expand All @@ -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<CancellationToken>,
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 {
Expand Down
Loading
Loading