Files
zag/README.md
T
Daniel Samson 4abc94f681
CI / test (pull_request) Successful in 3m20s
load levels: remove load levels from model, config, CLI, IPC, tests, docs
Completes issue #2 on top of the phase-1 strict single-job FIFO
scheduler. Removed:

- Job.load_level / Manifest.load_level / CreateOptions.load_level and
  the manifest.json loadLevel field (old manifests still parse: unknown
  fields are ignored)
- loadLevel in job JSON and <load_level> in XML output (field order
  shifts; old JSON still parses)
- the [load_levels] config section, service.max_concurrent_jobs,
  ZAG_LOAD_LEVELS_*/ZAG_LOADLEVELS_*/ZAG_SERVICE_MAX_CONCURRENT_JOBS
  env vars, loadlevel.zig / loadclass.zig and the default .load files

Friendly deprecation: old configs and environments still load fine.
config validate and config show report the removed settings as
non-fatal warnings (validate exit 1 stays reserved for real errors)
and the CLI/daemon logs them once at startup. --load-level is gone
from zag run; old IPC clients sending loadLevel are simply ignored.

e2e: wait_state is now portable to macOS bash 3.2 (it silently skipped
three checks before) and a serial-execution check asserts the second
job stays QUEUED while the first runs and both finish in FIFO order.
README and AGENTS.md document the deviation from barn.
2026-11-12 10:07:30 +00:00

264 lines
11 KiB
Markdown

# Zag Job Daemon (Cross-Platform)
> Zag is the [Zig](https://ziglang.org) port of
> [barn](https://gitea.samson.media/samson-media/barn), the Java job daemon. It keeps barn's
> CLI, JSON/XML output and job directory layout so clients can switch by changing the binary
> name, and fixes the places where barn's behaviour did not match its documentation (see
> [Migration from barn](#migration-from-barn)).
A **cross-platform (Linux and macOS) service** for managing long-running jobs that involve
downloading and uploading media via WebDAV, using FFmpeg to analyse and transcode video, with strong guarantees around durability,
observability, and crash recovery.
This project is designed to run as a **real OS service / daemon** on:
- macOS (launchd)
- Linux (systemd)
Windows is not supported.
The daemon is **not HTTP-bound**.
It runs independently in the background and exposes control via a local CLI / RPC interface.
---
## Why This Exists
Running FFmpeg jobs over SSH or ad-hoc scripts quickly breaks down when you need:
- Multiple concurrent jobs
- Reliable handling of failures
- Recovery after crashes or restarts
- Cross-platform support
- Programmatic job inspection and control
This project treats FFmpeg jobs as **first-class managed units of work**, not shell commands.
## Why Zig
Barn needs a JVM on every host that runs it. Zag aims to keep the same behaviour as a
single small, statically linked native binary, with no runtime to install, fast startup,
a low idle memory footprint, and easy cross-compilation to every supported platform.
---
## Core Goals
- Run FFmpeg jobs reliably in the background
- Survive SSH disconnects, restarts, and crashes
- Explicitly model job state and failure reasons
- Provide durable, inspectable job state
- Work consistently on Linux and macOS
- Avoid coupling to HTTP or web frameworks
- Stay drop-in compatible with barn's CLI, JSON/XML output, and job directory layout
---
## Installation
### Linux / macOS
The installer downloads the latest release, installs the binary and registers a service
(systemd on Linux, launchd on macOS):
```bash
curl -fsSL https://gitea.samson.media/samson-media/zag/raw/branch/main/install.sh | sh
```
`ZAG_VERSION`, `ZAG_PREFIX` and `ZAG_NO_SERVICE=1` tune the install; see the header of `install.sh`.
### Homebrew
```bash
brew tap samson-media/tap https://gitea.samson.media/samson-media/homebrew-tap
brew install zag
brew services start zag
```
### Manual
Download `zag-linux-x64`, `zag-linux-arm64`, `zag-macos-arm64` or `zag-macos-x64` from the
[releases page](https://gitea.samson.media/samson-media/zag/releases), check it against
`SHA256SUMS`, and put it on your `PATH`:
```bash
chmod +x zag-linux-x64 && sudo mv zag-linux-x64 /usr/local/bin/zag
zag --version
```
The binaries are static and need no runtime. Windows is not supported and there are no plans to add it.
### Setting up the service
```bash
sudo zag service install # system-wide (as root); without sudo it installs for your user
zag service start
zag service status
```
Once installed, `zag service start|stop|restart` go through systemd/launchd. Without
installing, `zag service start` runs a detached daemon of its own.
## Building
Requires Zig 0.16.0 or newer. Linux builds default to musl (a static binary).
```bash
zig build # build to zig-out/bin/zag
zig build test # unit tests
zig build e2e # end-to-end smoke test against the built binary
zig build -Doptimize=ReleaseSafe -Dstrip=true # release build (~1 MB)
```
Cross-compile with `-Dtarget`, for example:
```bash
zig build -Doptimize=ReleaseSafe -Dtarget=aarch64-macos
zig build -Doptimize=ReleaseSafe -Dtarget=x86_64-windows
zig build -Doptimize=ReleaseSafe -Dtarget=aarch64-linux
```
---
## Global options
| Option | Description |
|--------|-------------|
| `-o, --output {human\|json\|xml}` | Output format (default `human`) |
| `--config <file>` | Configuration file to merge on top of the system and user files |
| `--offline` | Run without the service: same code, in this process (`zag run --offline` executes the job and prints its final state) |
| `--barn-dir <dir>` | Data directory, overriding `storage.base_dir` (also relocates the socket) |
## Zag command
This project creates a simple CLI commandlet with sub-commands.
- `zag service {start|stop|restart|reload|status|logs|install|uninstall}` - manages the zag service
- `zag run {command}` - starts job
- `zag status` - gets the status of all jobs running
- `zag describe {jobId}` - collects all the info from /tmp and display it
- `zag usage {jobId}` - shows resource usage (CPU, memory, disk, GPU) for a job
- `zag kill {jobId}` - kills a job
- `zag clean` - performs clean up
- `zag config install` - installs default configuration files
- `zag config show` - shows effective configuration
- `zag config validate --file <path>` - checks a configuration file
- `zag config init` - writes a default user configuration file
- `zag autocompletion {--bash|--zsh}` - prints a shell completion script
zag is just one binary for both the service and the client. The client uses IPC to communicate with the service.
Clients typically access zag over ssh:
- fetch from webdav server: `zag run --output=json curl -u username:password -o /tmp/zag/input/video.mp4 https://example.com/dav/remote-file.ext`
- analyse file with ffmpeg: `zag run --output=json ffprobe -i /tmp/zag/input/video.mp4`
- get status of the jobs `zag status --output=json`
zag's output defaults to a human-readable format, but also supports xml or json via the `--output={json|xml}` cli option.
### Managing the service
There needs to be a zag service in order to run jobs (unless you use `--offline`). You manage the service using the `zag service` sub command.
- `zag service status` - check the status of the service. up/down, process id etc.
- `zag service start` - starts zag service process
- `zag service stop` - stops/kills the zag service
- `zag service restart` - restarts the zag service
- `zag service reload` - reloads the configuration and soft restarts the zag service
### Adding jobs
`zag run --output=json --tag=downloading <cmd>` takes in a command to run, starts a new process/thread, outputs the status of that job:
| Field | Description |
|---------------|--------------------------------------------------------|
| `job_id` | the id of the job |
| `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` |
| `tag` | user defined string |
| `created_at` | Job creation timestamp |
| `started_at` | Execution start timestamp |
| `finished_at` | Execution end timestamp |
| `exit_code` | '-' if still running, `0` or symbolic error code |
| `error` | Human-readable failure reason |
| `pid` | OS process ID (best-effort) |
| `heartbeat` | Last liveness update |
| `retryCount` | Current retry attempt (0 if never retried) |
| `retryAt` | Timestamp for next retry attempt (null if not retrying)|
Users can tag jobs for the purpose of filtering using the `--tag=string` CLI option.
Zag runs **one job at a time** (strict FIFO by creation order); there are no load levels.
Developers can use the `--offline` command line option to test how the service behaves (e.g., creating tmp files). This runs the same code as the service but without having to run the service.
### Get status of jobs
`zag status` gets the status of all jobs found in /tmp.
```
ID STATE TAG CREATED EXIT PID RETRIES NEXT RETRY
job-6d368040 succeeded - 2026-01-22 01:48:46 0 17486 - -
Total: 1 job (1 succeeded)
```
### Get details of a job
`zag describe {jobId}` - collects all the info from /tmp and display it
### Stop a job
`zag kill {jobId}` - kills a job process
### Clean up jobs
`zag clean` - removes completed jobs and cleans up old jobs (older than max_age config) from /tmp
---
## Concurrency
Zag runs **one job at a time**: jobs execute strictly in FIFO order by creation time. There
are no load levels, per-level limits, or `--load-level` override (barn had these; zag
intentionally does not — see [Migration from barn](#migration-from-barn)).
---
## Migration from barn
| Area | Barn | Zag |
|------|------|-----|
| Language | Java 21 (GraalVM native image) | Zig, static binary of about 1 MB |
| Binary | `barn` | `zag` |
| Data dir | `/tmp/barn` | `/tmp/zag` |
| Config | `/etc/barn/barn.conf`, `~/.config/barn/barn.conf` | `/etc/zag/zag.conf`, `~/.config/zag/zag.conf` |
| Environment overrides | `BARN_<SECTION>_<KEY>` | `ZAG_<SECTION>_<KEY>` (deprecated load-level variables are detected, warned about, and ignored) |
| Socket | `<base>/barn.sock` | `<base>/zag.sock` (mode 0600) |
The CLI surface, `--output={json|xml}` formats, job states and the on-disk job layout match
barn. Where barn's code disagreed with its own documentation, zag follows the documentation:
- `zag clean` behaves the same offline and through the service: with none of `--all`,
`--older-than` or `--job-id` it removes nothing.
- `kill` ends the job as `canceled` without racing the runner, and also cancels *queued* jobs.
- A failed job is **actually retried** (`--max-retries`, `--retry-delay`, `retry_on_exit_codes`,
exponential backoff with jitter); barn only retried jobs orphaned by a crash.
- `--timeout` and `default_timeout_seconds` are enforced (symbolic exit code `timeout`).
- `service reload` re-reads the configuration (also on SIGHUP) instead of doing nothing.
- `heartbeat_interval_seconds` is honoured, and `storage.base_dir` / `service.ipc_socket` are
used consistently by the daemon *and* the CLI.
- Jobs run in their own process group, so `kill` and `service stop --force` take down the whole
process tree. Job directories are created and deleted atomically.
- Zag runs **one job at a time** (strict FIFO); barn's load levels (high/medium/low
classification, per-level limits, `--load-level`, the `loadLevel` JSON/XML field and the
`LOAD` column of `zag status`) do not exist.
- Old configs and environments still load fine: `[load_levels]`, `max_concurrent_jobs`,
`ZAG_LOAD_LEVELS_*` and `ZAG_SERVICE_MAX_CONCURRENT_JOBS` are detected, reported as
non-fatal warnings, and ignored.
Not implemented: Windows (dropped on purpose), `max_disk_usage_gb`, `preserve_work_dir`, auto-update.
## Project Layout
See [AGENTS.md](AGENTS.md) for the module map. In short: `src/cli*.zig` is the command line,
`src/service.zig` the daemon core, `src/scheduler.zig` / `src/runner.zig` run jobs,
`src/repository.zig` persists them, `src/ipc.zig` is the socket protocol.