M9: figcraft-server checks its own health in a container, and runs with Docker Compose (#2044, part) (#2903)

figcraft-server healthcheck asks the server on the listen address for /healthz (exit 0 on 200, 1 otherwise), and the distroless image declares it as its HEALTHCHECK. packaging/server/docker-compose.yml builds the image and takes its FIGCRAFT_SERVER_* settings from a .env file beside it, with trusted_proxy defaulting to Docker's address range and the port on loopback. docs/server.md covers the subcommand, Compose, and running behind a platform proxy that ends TLS. Part of #2044.
This commit is contained in:
BFlat
2026-12-02 08:27:23 +07:00
committed by GitHub
parent 924f067d79
commit 92e3622177
6 changed files with 98 additions and 4 deletions
+2
View File
@@ -20,3 +20,5 @@ __pycache__/
/.nightly-input
/craft-i18n
/craft-fonts
# The Compose settings of a server run from this checkout
packaging/server/.env
+19 -1
View File
@@ -3,7 +3,8 @@
//! disconnects whoever joined with it at once); otherwise they change the directory themselves.
use std::fmt::Write as _;
use std::net::{IpAddr, SocketAddr};
use std::io::{Read as _, Write as _};
use std::net::{IpAddr, SocketAddr, TcpStream};
use std::path::{Path, PathBuf};
use std::time::Duration;
@@ -26,6 +27,7 @@ Usage:
figcraft-server [serve] [--listen ADDR] [--data DIR] [--public-url URL] [--config FILE]
figcraft-server key [--rotate] the address to publish to, with the server key
figcraft-server check check the settings (after editing the --config file)
figcraft-server healthcheck exit 0 if the server on the listen address answers /healthz
figcraft-server files [list] [--sort size|age|idle] the files kept (biggest, oldest or longest unopened first)
figcraft-server files remove FILE remove a file and its links for good
figcraft-server links list FILE a file's share links
@@ -84,6 +86,7 @@ pub enum Command {
RemovePlugin { id: String, version: Option<String> },
Reports,
Check,
Healthcheck,
Block { ip: String },
Unblock { ip: String },
Blocked,
@@ -163,6 +166,7 @@ pub fn parse_env(args: &[String], var: impl Fn(&str) -> Option<String>) -> Resul
["plugins", "remove", id] => Command::RemovePlugin { id: id.to_string(), version },
["reports"] => Command::Reports,
["check"] => Command::Check,
["healthcheck"] => Command::Healthcheck,
["block-ip", ip] => Command::Block { ip: ip.to_string() },
["unblock-ip", ip] => Command::Unblock { ip: ip.to_string() },
["blocked"] => Command::Blocked,
@@ -220,6 +224,7 @@ pub fn run(cli: &Cli) -> Result<String, String> {
Command::Check => {
Ok(format!("The settings are fine{}.\n", if cfg.open_publish { ": open to the public (anyone may publish without the key)" } else { "" }))
}
Command::Healthcheck => healthcheck(cfg),
Command::Reports => match admin(cfg, Admin::Reports)? {
AdminReply::Reports(reports) => Ok(reports_table(&reports)),
other => unexpected(other),
@@ -336,6 +341,19 @@ fn admin(cfg: &Config, req: Admin) -> Result<AdminReply, String> {
}
}
/// Ask the server on `listen` for `/healthz`: a container's health check, as the image has no curl.
fn healthcheck(cfg: &Config) -> Result<String, String> {
let addr = reachable(cfg.addr()?);
let fail = |e: std::io::Error| format!("no answer from {addr}: {e}");
let wait = Duration::from_secs(5);
let mut s = TcpStream::connect_timeout(&addr, wait).map_err(fail)?;
s.set_read_timeout(Some(wait)).map_err(fail)?;
s.write_all(b"GET /healthz HTTP/1.1\r\nHost: localhost\r\n\r\n").map_err(fail)?;
let mut reply = Vec::new();
s.take(64).read_to_end(&mut reply).map_err(fail)?;
if reply.starts_with(b"HTTP/1.1 200") { Ok("ok\n".into()) } else { Err(format!("{addr} isn't a healthy figcraft-server")) }
}
/// The address to publish to, with the key.
fn key(cfg: &Config, rotate: bool) -> Result<String, String> {
let mut store = Store::try_open(&cfg.data, cfg.store())?;
+11
View File
@@ -145,3 +145,14 @@ fn the_environment_overrides_the_config_file_and_flags_override_it() {
assert_eq!(parse_env(&args(&["--help"]), bad).unwrap().command, Command::Help);
assert_eq!(parse_env(&args(&["--version"]), bad).unwrap().command, Command::Version);
}
#[test]
fn healthcheck_needs_a_server_answering() {
let dir = TempDir::new("healthcheck");
let mut server = crate::start(&config(dir.path())).unwrap();
let cfg = Config { listen: server.addr().to_string(), ..config(dir.path()) };
let check = || cli::run(&Cli { config: cfg.clone(), command: Command::Healthcheck });
assert!(check().is_ok());
server.stop();
assert!(check().is_err());
}
+32 -2
View File
@@ -37,7 +37,9 @@ Releases also ship it ready-built for Linux (`figcraft-server-<version>-linux-x8
lines (`event=published file=… bytes=… ip=… by=public`, `event=refused ip=… reason=…`,
`event=report`, `event=expired`, `event=blocked`).
- `GET /healthz` on the same port answers `200 ok` (on any path ending in `/healthz`), for uptime
checks; nothing else listens.
checks; nothing else listens. `figcraft-server healthcheck` asks the server on the `listen`
address for it and exits 0 when it answers, for a container's health check where there is no
`curl`.
- Stop it like any service (Ctrl+C, `systemctl stop`, `docker stop`, `kill`): on SIGTERM, SIGINT
or SIGHUP (Ctrl+C or closing the console on Windows) it saves and compacts the open files and
tells everyone it is restarting. Every change it accepted is on disk before anyone is told about
@@ -327,6 +329,7 @@ port as everything else; no other service is involved.
|---|---|
| `figcraft-server key [--rotate]` | The address to publish to, with the key; `--rotate` makes a new key (the server must be stopped) |
| `figcraft-server check` | Check the settings (after editing the `--config` file) |
| `figcraft-server healthcheck` | Exit 0 if the server on the `listen` address answers `/healthz`, 1 if not |
| `figcraft-server files [list] [--sort size\|age\|idle]` | The files: id, name, people in it now, size, created, days unused, expiry, reports, and who published it (`key`, or the address of a file published without it); biggest, oldest or longest unused first |
| `figcraft-server files remove FILE` | Remove a file and its links for good (whoever is in it is disconnected) |
| `figcraft-server links list FILE` | A file's links: id, access, created, label |
@@ -812,6 +815,32 @@ docker run -d --name figcraft-server --restart unless-stopped -p 127.0.0.1:47900
docker exec figcraft-server /usr/local/bin/figcraft-server --config /etc/figcraft-server/server.toml key
```
The image checks its own health (`figcraft-server healthcheck`, every 30 seconds), so
`docker ps` shows it `healthy` once it serves.
**With Docker Compose.** [`packaging/server/docker-compose.yml`](../packaging/server/docker-compose.yml)
builds the same image and takes its settings from a `.env` file beside it instead of a settings
file: one variable a line, each key as `FIGCRAFT_SERVER_` and the key in capitals (see
[Configuration](#configuration)), for example `FIGCRAFT_SERVER_TEAM_FILES=view`. Compose refuses
to start without the file, and upgrades read it again. It publishes the port on the loopback interface for the proxy from step 4 and trusts that
proxy's connections from Docker's address range (`172.16.0.0/12`; set
`FIGCRAFT_SERVER_TRUSTED_PROXY` to change it):
```sh
cd packaging/server
echo FIGCRAFT_SERVER_PUBLIC_URL=wss://figcraft.example.com/ > .env
docker compose up -d --build
docker compose exec figcraft-server figcraft-server --config /etc/figcraft-server/server.toml key
```
On a platform that puts its own proxy in front of containers and ends TLS there, give the
server the platform's `https://` address as `wss://` in `FIGCRAFT_SERVER_PUBLIC_URL`, set
`FIGCRAFT_SERVER_TRUSTED_PROXY` to the range the proxy connects from, and point the platform's
health check at `/healthz` or `figcraft-server healthcheck`. The proxy must pass WebSocket
upgrades through and allow connections that stay open (apps ping every 15 seconds). The server
key is made on the first start and kept in the data volume; `figcraft-server key` (run in the
container as above) prints the address to publish to.
**Upgrading.** Install the new binary as in step 1, then restart: the restart is graceful and apps
reconnect on their own. An app speaking another protocol version is refused with a message saying
so: upgrade apps and server together when the release notes say the protocol changed.
@@ -821,7 +850,8 @@ sudo systemctl restart figcraft-server
```
With Docker: rebuild the image, then `docker rm -f figcraft-server` and the `docker run` above
again (the volume keeps the files).
again (the volume keeps the files); with Compose, `docker compose up -d --build` in
`packaging/server` (it reads `.env` again).
**Backups.** See [Backups](#backups); with systemd, for example:
+4 -1
View File
@@ -5,7 +5,8 @@
#
# The image runs as an unprivileged user, keeps its files in the /data volume and reads
# /etc/figcraft-server/server.toml (listen on 0.0.0.0:47900, data in /data; mount your own to set
# public_url). `docker stop` sends SIGTERM: the server saves open files and stops gracefully.
# public_url, or set it as FIGCRAFT_SERVER_PUBLIC_URL). `docker stop` sends SIGTERM: the server
# saves open files and stops gracefully. docker-compose.yml beside this file runs it with Compose.
FROM rust:1-bookworm AS build
WORKDIR /src
@@ -23,4 +24,6 @@ USER nonroot
VOLUME /data
EXPOSE 47900
STOPSIGNAL SIGTERM
# No curl in the image: the server asks itself for /healthz.
HEALTHCHECK --interval=30s --timeout=10s --start-period=10s CMD ["/usr/local/bin/figcraft-server", "--config", "/etc/figcraft-server/server.toml", "healthcheck"]
ENTRYPOINT ["/usr/local/bin/figcraft-server", "--config", "/etc/figcraft-server/server.toml"]
+30
View File
@@ -0,0 +1,30 @@
# figcraft-server with Docker Compose; setup in docs/server.md ("With Docker Compose"). From this
# directory, with a TLS reverse proxy on this machine in front of port 47900:
#
# echo FIGCRAFT_SERVER_PUBLIC_URL=wss://figcraft.example.com/ > .env
# docker compose up -d --build
# docker compose exec figcraft-server figcraft-server --config /etc/figcraft-server/server.toml key
#
# .env holds the settings, one FIGCRAFT_SERVER_* variable a line (docs/server.md, "Configuration");
# upgrades read it again.
# The image's health check asks the server for /healthz.
services:
figcraft-server:
build:
context: ../..
dockerfile: packaging/server/Dockerfile
image: figcraft-server
restart: unless-stopped
env_file: .env
environment:
# Where the proxy's connections come from (the containers' address range), so the limits
# per address count the people behind it.
FIGCRAFT_SERVER_TRUSTED_PROXY: ${FIGCRAFT_SERVER_TRUSTED_PROXY:-172.16.0.0/12}
# Loopback only: ports Docker publishes bypass the firewall, so the proxy is the way in.
ports:
- "127.0.0.1:47900:47900"
volumes:
- figcraft-data:/data
volumes:
figcraft-data: