Skip to main content
The axe crate is the engine axed runs, with no network code and no daemon.
axe builds on Linux only. On any other target the crate stops with compile_error!("axe targets Linux"). On macOS, build and run inside a Linux container, as described in Develop on macOS.

Add the dependency

The crate is not published to crates.io. Add it as a git dependency. The package name is axe.
Cargo.toml
The engine runs on Tokio. axe enables the Tokio features it needs itself (rt, net, io-util, sync, time, macros). Your program needs a runtime to call it from. rt-multi-thread and macros give you #[tokio::main]. Creating the Supervisor needs no runtime, but call Supervisor::spawn from inside one, because the runtime drives every process it starts. Pin a commit with rev = "..." if you want reproducible builds. The crate’s minimum Rust version is 1.88 and it uses edition 2024.

The engine owns wait

The engine reaps every child of your program from one thread with wait4(-1). It also marks your program as a child subreaper, so orphaned grandchildren come back to it.
Never wait for children yourself. std::process::Child::wait, waitpid and tokio::process race with the engine’s reaper. Either side can collect an exit the other is waiting for. Start every process through Supervisor::spawn.

Core types

How they fit

  1. Open a Root for the workspace. Resolve working directories with root.dir(path), which is the only way to get the WorkDir a Command needs.
  2. Create one Supervisor, with or without Cgroups.
  3. Build a Command and call supervisor.spawn(command, options). It returns (Arc<Process>, Option<Reader>) once the process is running. Or call supervisor.capture(command, limits).await to run it to completion and keep its output.
  4. Read output through a Reader, from the spawn or later from process.reader(from, delivery)?, or through process.events(reader, replay) to get the exit at the end.
  5. Call process.wait().await for the Exit.
  6. Call supervisor.shutdown(grace).await before your program exits.

SpawnOptions

Config

Supervisor::new fails with Error::InvalidArgument when chunk_size or max_processes is 0, when default_retain_bytes exceeds max_retain_bytes, or when child_oom_score_adj is outside -1000 to 1000. Otherwise it raises default_retain_bytes to at least chunk_size, max_retain_bytes to at least that, and output_budget_bytes to at least the raised max_retain_bytes.

Command

Limits fields: A WorkDir holds the directory’s host path as Root resolved it, and the kernel resolves that path again when the process starts. Resolution cannot leave the root, but a path component swapped for a symlink between the two lookups can still redirect the starting directory. The race grants the process nothing it could not do itself with chdir.

Stream output as it arrives

This program runs a command, prints each chunk with its stream and offset, and reports the exit.
src/main.rs
It prints:
Offsets count bytes in one log that combines stdout and stderr, so the interleaving survives replay. The chunk’s stream_offset field gives the position within the chunk’s own stream, for protocols that address the two separately. process.events(reader, replay) turns any reader into output followed by the exit. Replay::Follow waits for output until the log ends, then yields Event::Exited. Replay::Snapshot yields only what is retained now, and ends with Event::Exited only if the process has already exited. Gaps appear if the reader is lossy, or once at the start if it was opened at an offset already evicted. events.next() is cancel-safe, so it can sit in a tokio::select!.

Run a command to completion

supervisor.capture(command, limits).await runs a command, keeps a prefix of each stream, and returns Captured { exit, stdout, stderr, elapsed }. Each stream is a Capture { data, truncated }.
src/main.rs
  • A limit of 0, or anything above axe::MAX_CAPTURE_BYTES (256 MiB), keeps up to 256 MiB of that stream.
  • Kept bytes count against Config::capture_budget_bytes, shared by every capture, until you drop data (and every clone of it). A capture never waits for memory: output past its limit or past what the budget has left is dropped and reported as truncated, and the kept bytes are always a prefix of the stream.
  • The process belongs to the future. Dropping it before the process exits kills the tree. The record is not kept after exit.

Retry a capture safely

supervisor.capture_once(command, limits, request_id, retain_bytes).await is a capture you can repeat, for a caller that may lose the first answer, as a client does across a snapshot. The process is kept like a spawn with keep, retaining retain_bytes of output (0 for the default), and it runs to the end even if the future is dropped. Repeating the call with the same request id, command (its Limits included) and retain_bytes collects the first run’s process instead of starting another, reading its output back from the retained log, so the command runs once. Once that output or the record is evicted, the repeat fails with Error::RequestExpired.
src/main.rs

Tie a process to its caller

Owned::new(process) wraps an Arc<Process>. When the Owned is dropped while the process is still running, it kills the tree with kill_tree. Use it to give a process the lifetime of a request or a connection: hold the Owned in the task serving the client, and the process dies when the client goes away. Owned dereferences to Process, and owned.process() gives the Arc back.
src/main.rs

Run a detached process and reattach

A detached process has no reader at spawn. Its output goes to a bounded log that you can read later from any retained offset.
src/main.rs
Things to know about readers:
  • process.reader(Some(offset), delivery) starts at offset, clamped to the end of the log. process.reader(None, delivery) starts at the oldest retained byte. It returns axe::Result<Reader>. A process allows at most 64 lossless readers at once (axe::output::MAX_LOSSLESS_READERS), and one more fails with Error::ResourceExhausted. Lossy readers are not limited.
  • If offset was already evicted, the reader first returns Item::Gap { from, to } and continues at the oldest retained byte. A lossy reader also gets a gap whenever it falls behind the retained window later.
  • reader.try_next() returns what is available now and None when caught up. reader.next().await waits for more and returns None after the process exits and the log is drained.
  • To resume later without replaying, keep the offset after the last byte you read: chunk.offset + chunk.data.len() for a chunk, or to for a gap. Pass it as Some(offset) to a new reader.
  • A lossless reader holds the process back once retention is full. Drop it when you stop reading.
To find a process again, use supervisor.get(id), supervisor.get_by_name(name) (the running process with that name, or else the most recently finished kept one), or supervisor.list() (oldest first). A ProcessId prints as 32 lowercase hex digits and parses back from exactly that with str::parse; anything else fails with Error::InvalidArgument. The output log behind process.output() is read-only to you. Only the engine writes to it or ends it. Use it for window() and is_closed(), and open readers through process.reader.

Exit fields

ExitReason is #[non_exhaustive]: When the engine kills a tree, the first cause it acted on wins, whatever status that left. A process that had already exited on its own when the engine acted keeps Exited or Signaled. If the program in the example exits through its trap, status is Exited(0), signal() is None and reason is Exited. A process killed by SIGTERM reports code 143, Some(15) and Signaled.

Usage while running

process.usage() returns a LiveUsage for a running process: user_cpu, system_cpu, memory_bytes, peak_memory_bytes (Option) and tasks, and a scope. With a cgroup the figures cover the whole tree (UsageScope::Tree), read from cpu.stat, memory.current, memory.peak and pids.current. Without one they cover only the leader (UsageScope::Leader), from /proc/<pid>/stat, and peak_memory_bytes is None. Each call reads a few small files; nothing samples in the background. It returns None once the process has exited, when Exit::usage has the totals. process.has_cgroup() tells which applies.

Stop a process

Pick the call by what you want to happen. Use signal with SIGTERM or SIGINT to ask a process to stop and let it clean up, then wait. Use kill_tree when you need the process and everything it started gone now; follow it with wait if you need the exit. Use remove to free a finished record’s retention and table slot, with IfRunning::Kill to stop and forget in one step. signal is a no-op once the leader has exited, even while its output is still draining, so a signal never reaches a process that has since reused its pid. It returns Error::InvalidArgument for an invalid signal number and Error::PermissionDenied when the kernel refuses.
Processes in a pipeline or a shell often ignore SIGTERM sent only to the leader. SignalTarget::Group signals the whole group, which is what a terminal does.

Work with files

Root resolves every path one component at a time against directory descriptors it holds, so neither .. nor a symlink, even one swapped in mid-request, can lead outside it. Absolute paths under the root have the root stripped. Other absolute paths fail with Error::PermissionDenied. root.lenient()? returns a second handle on the same directory that takes an absolute path outside the root as relative to it, so /etc/passwd names etc/passwd inside the root. That is the Kubernetes Agent Sandbox convention, and axed uses it for that protocol only. Confinement is the same in both modes. .. and symlinks still cannot leave the root.
src/main.rs
Root methods are blocking. In an async program, call them from tokio::task::spawn_blocking when they may take a while (large listings, copies, archive extraction). Watcher::new(&root, path, recursive) arms an inotify watch on a directory. next_batch(window).await waits for at least one event, keeps collecting for window, and returns the events in order. A batch stops early at about 4,096 events; the rest wait in the kernel’s queue, which reports an overflow if it fills. An empty batch means the watch ended. Paths in events are relative to the root. A rename is reported on the old path, and the new path arrives as a Create when it lands inside the watched tree. Uploads in progress through create are not reported until they commit.

Cgroups and the lifecycle

Pass Some(Cgroups) to Supervisor::new to place each process in its own cgroup, named p plus its process id. Cgroups::setup(Path::new("/sys/fs/cgroup"), leaf) takes over the cgroup your program runs in: it moves your program into a child cgroup named leaf (axed passes axed), removes per-process cgroups left by an earlier run (killing anything still in them), and enables the cpu, memory and pids controllers for per-process children. It fails with Error::FailedPrecondition when cgroup v2 is not mounted in unified mode, or when other processes share the cgroup and your program is not PID 1.
src/main.rs
Without cgroups, processes run in their own process groups under rlimits, cpu_millis is refused, and supervisor.set_frozen(frozen, timeout).await fails with Error::FailedPrecondition. With cgroups, set_frozen freezes or thaws every process tree, including what finished processes left running with Leftovers::Leave, and returns how many trees changed state before the timeout and how many there were. From a freeze until the thaw, spawn and capture fail with Error::Frozen, so nothing starts while the rest are stopped; supervisor.is_frozen() tells whether that is the case. cgroups.reserve_memory(bytes) sets memory.min on the leaf your program moved into, so reclaim takes the supervised trees’ memory first. It fails without the memory controller. axed reserves 16 MiB. supervisor.lifecycle() returns the Lifecycle: axe::lifecycle::add_entropy(bytes) credits bytes to the kernel entropy pool after a restore. It needs CAP_SYS_ADMIN. Snapshots explains when to call these.

Develop on macOS

The repository’s scripts/dev runs any command in a Linux container with a Rust toolchain:
examples/embed.rs is a complete program in the repository. For your own crate, run Cargo in any Linux container or VM with your project mounted.

Read the API documentation

The crate documents every public type, starting with a quickstart. On Linux, from your project or the AXE repository:
On macOS, scripts/dev keeps build output in a Docker volume, so the HTML stays inside it. Point CARGO_TARGET_DIR at a directory in your checkout to get it on the host:

Next steps