Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6325a87670 | ||
|
|
18c77a6e96 | ||
|
|
5ee6b6021c | ||
|
|
3a4c4fa326 | ||
|
|
4abc94f681 | ||
|
|
8f3f61c86a | ||
|
|
575c895306 |
No files matched your search
@@ -16,6 +16,9 @@ Guidance for AI coding agents working in `zag`, the Zig port of the
|
|||||||
- Keep CLI flags, JSON/XML output field order, config defaults and the on-disk job
|
- Keep CLI flags, JSON/XML output field order, config defaults and the on-disk job
|
||||||
directory layout compatible with barn (`zag` replaces `barn` in names and paths).
|
directory layout compatible with barn (`zag` replaces `barn` in names and paths).
|
||||||
- Port specs from barn's unit tests alongside each module (`test` blocks).
|
- Port specs from barn's unit tests alongside each module (`test` blocks).
|
||||||
|
- **Intentional deviation (issue #2)**: zag runs only one job at a time (strict FIFO);
|
||||||
|
barn's load levels are gone. Old `[load_levels]` / `max_concurrent_jobs` settings and
|
||||||
|
`ZAG_LOAD_LEVELS_*` env vars still load, are reported as non-fatal warnings, and ignored.
|
||||||
|
|
||||||
## Layout
|
## Layout
|
||||||
|
|
||||||
@@ -28,19 +31,17 @@ Guidance for AI coding agents working in `zag`, the Zig port of the
|
|||||||
| `src/fsutil.zig` | Atomic writes, trimmed reads, advisory `FileLock` |
|
| `src/fsutil.zig` | Atomic writes, trimmed reads, advisory `FileLock` |
|
||||||
| `src/jsonpretty.zig` | Streaming JSON writer matching Jackson `INDENT_OUTPUT` layout |
|
| `src/jsonpretty.zig` | Streaming JSON writer matching Jackson `INDENT_OUTPUT` layout |
|
||||||
| `src/toml.zig` | Parser for barn's TOML subset (`[section]`, `key = value`, arrays) |
|
| `src/toml.zig` | Parser for barn's TOML subset (`[section]`, `key = value`, arrays) |
|
||||||
| `src/loadlevel.zig` | `high`/`medium`/`low` load levels |
|
|
||||||
| `src/job.zig` | `Job`, `Manifest`, `ExitCode` types |
|
| `src/job.zig` | `Job`, `Manifest`, `ExitCode` types |
|
||||||
| `src/dirs.zig` | On-disk layout under the base dir |
|
| `src/dirs.zig` | On-disk layout under the base dir |
|
||||||
| `src/statefiles.zig` | One-value-per-file job state (atomic) |
|
| `src/statefiles.zig` | One-value-per-file job state (atomic) |
|
||||||
| `src/repository.zig` | Job create/find/transition/retry persistence, `manifest.json` I/O |
|
| `src/repository.zig` | Job create/find/transition/retry persistence, `manifest.json` I/O |
|
||||||
| `src/config.zig` | Config structs, defaults, TOML loading/merging, `ZAG_*` env overrides, validation |
|
| `src/config.zig` | Config structs, defaults, TOML loading/merging, `ZAG_*` env overrides, validation, deprecated-setting warnings |
|
||||||
| `src/loadclass.zig` | `.load` whitelist parsing and load-level classifier |
|
| `src/defaults.zig`, `src/defaults/` | Default `zag.conf` embedded in the binary |
|
||||||
| `src/defaults.zig`, `src/defaults/` | Default `zag.conf` and `*.load` files embedded in the binary |
|
|
||||||
| `src/retry.zig` | Retry decision and backoff/jitter delay |
|
| `src/retry.zig` | Retry decision and backoff/jitter delay |
|
||||||
| `src/proc.zig` | Spawn with log redirection, process-group signals, liveness |
|
| `src/proc.zig` | Spawn with log redirection, process-group signals, liveness |
|
||||||
| `src/runner.zig` | Runs one job: heartbeat, timeout, kill, completion, retry |
|
| `src/runner.zig` | Runs one job: heartbeat, timeout, kill, completion, retry |
|
||||||
| `src/recovery.zig` | Startup crash recovery of orphaned running jobs |
|
| `src/recovery.zig` | Startup crash recovery of orphaned running jobs |
|
||||||
| `src/scheduler.zig` | Per-load-level concurrency, thread per job, `killJob` |
|
| `src/scheduler.zig` | Strict single-job FIFO scheduling, thread per job, `killJob` |
|
||||||
| `src/usage.zig` | `ps`/`nvidia-smi` sampling, `usage.csv`, summaries |
|
| `src/usage.zig` | `ps`/`nvidia-smi` sampling, `usage.csv`, summaries |
|
||||||
| `src/cleanup.zig` | Automatic and manual (`zag clean`) cleanup planning |
|
| `src/cleanup.zig` | Automatic and manual (`zag clean`) cleanup planning |
|
||||||
| `src/jobjson.zig` | `Job` JSON (shared by CLI `--output=json` and IPC) |
|
| `src/jobjson.zig` | `Job` JSON (shared by CLI `--output=json` and IPC) |
|
||||||
|
|||||||
@@ -172,7 +172,6 @@ There needs to be a zag service in order to run jobs (unless you use `--offline`
|
|||||||
|---------------|--------------------------------------------------------|
|
|---------------|--------------------------------------------------------|
|
||||||
| `job_id` | the id of the job |
|
| `job_id` | the id of the job |
|
||||||
| `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` |
|
| `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` |
|
||||||
| `load_level` | `HIGH`, `MEDIUM`, or `LOW` (auto-detected or manual) |
|
|
||||||
| `tag` | user defined string |
|
| `tag` | user defined string |
|
||||||
| `created_at` | Job creation timestamp |
|
| `created_at` | Job creation timestamp |
|
||||||
| `started_at` | Execution start timestamp |
|
| `started_at` | Execution start timestamp |
|
||||||
@@ -186,7 +185,7 @@ There needs to be a zag service in order to run jobs (unless you use `--offline`
|
|||||||
|
|
||||||
Users can tag jobs for the purpose of filtering using the `--tag=string` CLI option.
|
Users can tag jobs for the purpose of filtering using the `--tag=string` CLI option.
|
||||||
|
|
||||||
Jobs are automatically assigned a **load level** based on the command being run (see [Load Levels](#load-levels)). You can override this with `--load-level={high|medium|low}`.
|
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.
|
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.
|
||||||
|
|
||||||
@@ -195,8 +194,8 @@ Developers can use the `--offline` command line option to test how the service b
|
|||||||
`zag status` gets the status of all jobs found in /tmp.
|
`zag status` gets the status of all jobs found in /tmp.
|
||||||
|
|
||||||
```
|
```
|
||||||
ID STATE LOAD TAG CREATED EXIT PID RETRIES NEXT RETRY
|
ID STATE TAG CREATED EXIT PID RETRIES NEXT RETRY
|
||||||
job-6d368040 succeeded medium - 2026-01-22 01:48:46 0 17486 - -
|
job-6d368040 succeeded - 2026-01-22 01:48:46 0 17486 - -
|
||||||
|
|
||||||
Total: 1 job (1 succeeded)
|
Total: 1 job (1 succeeded)
|
||||||
```
|
```
|
||||||
@@ -215,35 +214,11 @@ Total: 1 job (1 succeeded)
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Load Levels
|
## Concurrency
|
||||||
|
|
||||||
Zag supports **per-level job limits** to allow concurrent execution of different types of jobs. For example, you can run multiple downloads while transcoding without overwhelming the system.
|
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
|
||||||
### Load Level Types
|
intentionally does not — see [Migration from barn](#migration-from-barn)).
|
||||||
|
|
||||||
| Level | Default Max | Use Case |
|
|
||||||
|-------|-------------|----------|
|
|
||||||
| HIGH | 2 | CPU/GPU intensive (transcoding, encoding) |
|
|
||||||
| MEDIUM | 8 | General purpose commands |
|
|
||||||
| LOW | 32 | Network/IO intensive (downloads, uploads) |
|
|
||||||
|
|
||||||
### Auto-Classification
|
|
||||||
|
|
||||||
Jobs are automatically classified based on whitelist files in `/etc/zag/`:
|
|
||||||
|
|
||||||
- `high.load` - ffmpeg, ffprobe, handbrake, x264, x265, etc.
|
|
||||||
- `medium.load` - general commands (default if not matched)
|
|
||||||
- `low.load` - curl, wget, rclone, rsync, aria2c, etc.
|
|
||||||
|
|
||||||
### Manual Override
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Run ffmpeg as LOW load (bypass normal HIGH classification)
|
|
||||||
zag run --load-level=low -- ffmpeg -i input.mp4 output.mp4
|
|
||||||
|
|
||||||
# Run curl as HIGH load (override normal LOW classification)
|
|
||||||
zag run --load-level=high -- curl -O https://example.com/file.zip
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -255,12 +230,11 @@ zag run --load-level=high -- curl -O https://example.com/file.zip
|
|||||||
| Binary | `barn` | `zag` |
|
| Binary | `barn` | `zag` |
|
||||||
| Data dir | `/tmp/barn` | `/tmp/zag` |
|
| Data dir | `/tmp/barn` | `/tmp/zag` |
|
||||||
| Config | `/etc/barn/barn.conf`, `~/.config/barn/barn.conf` | `/etc/zag/zag.conf`, `~/.config/zag/zag.conf` |
|
| 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>` (`ZAG_LOAD_LEVELS_MAX_HIGH_JOBS` works) |
|
| 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) |
|
| Socket | `<base>/barn.sock` | `<base>/zag.sock` (mode 0600) |
|
||||||
|
|
||||||
The CLI surface, `--output={json|xml}` formats, job states, load levels and the on-disk job
|
The CLI surface, `--output={json|xml}` formats, job states and the on-disk job layout match
|
||||||
layout match barn. Where barn's code disagreed with its own documentation, zag follows the
|
barn. Where barn's code disagreed with its own documentation, zag follows the documentation:
|
||||||
documentation:
|
|
||||||
|
|
||||||
- `zag clean` behaves the same offline and through the service: with none of `--all`,
|
- `zag clean` behaves the same offline and through the service: with none of `--all`,
|
||||||
`--older-than` or `--job-id` it removes nothing.
|
`--older-than` or `--job-id` it removes nothing.
|
||||||
@@ -273,9 +247,12 @@ documentation:
|
|||||||
used consistently by the daemon *and* the CLI.
|
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
|
- 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.
|
process tree. Job directories are created and deleted atomically.
|
||||||
- Without `config install`, the built-in `.load` lists still classify `ffmpeg` as HIGH and
|
- Zag runs **one job at a time** (strict FIFO); barn's load levels (high/medium/low
|
||||||
`curl` as LOW.
|
classification, per-level limits, `--load-level`, the `loadLevel` JSON/XML field and the
|
||||||
- `config show` calls the load-limit section `load_levels`, matching the config file.
|
`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.
|
Not implemented: Windows (dropped on purpose), `max_disk_usage_gb`, `preserve_work_dir`, auto-update.
|
||||||
|
|
||||||
|
|||||||
+12
-2
@@ -36,6 +36,8 @@ pub const Context = struct {
|
|||||||
config_value: config.Config = .{},
|
config_value: config.Config = .{},
|
||||||
config_error: ?config.Error = null,
|
config_error: ?config.Error = null,
|
||||||
config_diag: config.Diagnostic = .{},
|
config_diag: config.Diagnostic = .{},
|
||||||
|
/// Deprecation warnings collected while loading the config; printed once per process.
|
||||||
|
config_deprecations: std.ArrayList(config.Problem) = .empty,
|
||||||
|
|
||||||
pub fn flag(self: *const Context, name: []const u8) bool {
|
pub fn flag(self: *const Context, name: []const u8) bool {
|
||||||
return self.parsed.flag(name);
|
return self.parsed.flag(name);
|
||||||
@@ -71,8 +73,14 @@ pub const Context = struct {
|
|||||||
fn loadConfigOnce(self: *Context) void {
|
fn loadConfigOnce(self: *Context) void {
|
||||||
if (self.config_loaded) return;
|
if (self.config_loaded) return;
|
||||||
self.config_loaded = true;
|
self.config_loaded = true;
|
||||||
if (config.load(self.arena, self.io, self.env, .{ .explicit_path = self.value("config") }, &self.config_diag)) |c| {
|
if (config.load(self.arena, self.io, self.env, .{ .explicit_path = self.value("config") }, &self.config_diag, &self.config_deprecations)) |c| {
|
||||||
self.config_value = c;
|
self.config_value = c;
|
||||||
|
for (self.config_deprecations.items) |w| {
|
||||||
|
self.stderr.print("warning: {s}\n", .{w.message}) catch {};
|
||||||
|
}
|
||||||
|
// The daemon's stderr is a buffered writer over logs/zag.log; flush so the
|
||||||
|
// warnings reach the log at startup, not on process exit.
|
||||||
|
if (self.config_deprecations.items.len > 0) self.stderr.flush() catch {};
|
||||||
} else |err| {
|
} else |err| {
|
||||||
self.config_error = err;
|
self.config_error = err;
|
||||||
}
|
}
|
||||||
@@ -423,7 +431,9 @@ test "per-command help" {
|
|||||||
defer arena.deinit();
|
defer arena.deinit();
|
||||||
const r = try runCaptured(arena.allocator(), &.{ "run", "--help" }, null);
|
const r = try runCaptured(arena.allocator(), &.{ "run", "--help" }, null);
|
||||||
try std.testing.expectEqual(exit_ok, r.code);
|
try std.testing.expectEqual(exit_ok, r.code);
|
||||||
try std.testing.expect(std.mem.indexOf(u8, r.out, "--load-level") != null);
|
try std.testing.expect(std.mem.indexOf(u8, r.out, "--tag") != null);
|
||||||
|
// issue #2 removed the load levels: the flag must not resurface in the help.
|
||||||
|
try std.testing.expect(std.mem.indexOf(u8, r.out, "load-level") == null);
|
||||||
const s = try runCaptured(arena.allocator(), &.{ "service", "--help" }, null);
|
const s = try runCaptured(arena.allocator(), &.{ "service", "--help" }, null);
|
||||||
try std.testing.expect(std.mem.indexOf(u8, s.out, "restart") != null);
|
try std.testing.expect(std.mem.indexOf(u8, s.out, "restart") != null);
|
||||||
}
|
}
|
||||||
+51
-45
@@ -21,7 +21,6 @@ const proc = @import("proc.zig");
|
|||||||
const timestamp = @import("timestamp.zig");
|
const timestamp = @import("timestamp.zig");
|
||||||
const Repository = @import("repository.zig").Repository;
|
const Repository = @import("repository.zig").Repository;
|
||||||
const state_mod = @import("state.zig");
|
const state_mod = @import("state.zig");
|
||||||
const Classifier = @import("loadclass.zig").Classifier;
|
|
||||||
const jsonpretty = @import("jsonpretty.zig");
|
const jsonpretty = @import("jsonpretty.zig");
|
||||||
const servicemgr = @import("servicemgr.zig");
|
const servicemgr = @import("servicemgr.zig");
|
||||||
|
|
||||||
@@ -57,7 +56,14 @@ const ReloadState = struct {
|
|||||||
|
|
||||||
fn reloadConfig(ctx_ptr: ?*anyopaque, arena: Allocator) anyerror!config.Config {
|
fn reloadConfig(ctx_ptr: ?*anyopaque, arena: Allocator) anyerror!config.Config {
|
||||||
const st: *const ReloadState = @ptrCast(@alignCast(ctx_ptr.?));
|
const st: *const ReloadState = @ptrCast(@alignCast(ctx_ptr.?));
|
||||||
return config.load(arena, st.io, st.env, .{ .explicit_path = st.explicit_path }, null);
|
// Use a local list so its backing array is owned by this reload's arena and
|
||||||
|
// never outlives the call — avoids use-after-free across successive reloads.
|
||||||
|
var warnings: std.ArrayList(config.Problem) = .empty;
|
||||||
|
const cfg = try config.load(arena, st.io, st.env, .{ .explicit_path = st.explicit_path }, null, &warnings);
|
||||||
|
// The daemon's stderr is its log file (or the journal under a service manager):
|
||||||
|
// deprecation warnings must reach it on every reload, not only at startup.
|
||||||
|
for (warnings.items) |p| std.log.warn("{s}", .{p.message});
|
||||||
|
return cfg;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn startBackground(ctx: *Context) !u8 {
|
fn startBackground(ctx: *Context) !u8 {
|
||||||
@@ -125,14 +131,11 @@ pub fn cmdServiceStart(ctx: *Context) !u8 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
logging.setFromConfig(cfg.service.log_level);
|
logging.setFromConfig(cfg.service.log_level);
|
||||||
const sys_dir = try config.systemConfigDir(ctx.arena, ctx.env);
|
|
||||||
const classifier = try Classifier.loadOrDefaults(ctx.arena, ctx.io, sys_dir);
|
|
||||||
const reload_state = try ctx.arena.create(ReloadState);
|
const reload_state = try ctx.arena.create(ReloadState);
|
||||||
reload_state.* = .{ .io = ctx.io, .env = ctx.env, .explicit_path = ctx.value("config") };
|
reload_state.* = .{ .io = ctx.io, .env = ctx.env, .explicit_path = ctx.value("config") };
|
||||||
|
|
||||||
var svc = service_mod.Service.init(ctx.gpa, ctx.io, &dirs, .{
|
var svc = service_mod.Service.init(ctx.gpa, ctx.io, &dirs, .{
|
||||||
.config = cfg,
|
.config = cfg,
|
||||||
.classifier = classifier,
|
|
||||||
.reload_fn = reloadConfig,
|
.reload_fn = reloadConfig,
|
||||||
.reload_ctx = reload_state,
|
.reload_ctx = reload_state,
|
||||||
});
|
});
|
||||||
@@ -554,11 +557,10 @@ pub const config_show_usage =
|
|||||||
\\
|
\\
|
||||||
;
|
;
|
||||||
|
|
||||||
fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8) !Node {
|
fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8, warnings: []const config.Problem) !Node {
|
||||||
var root = MapBuilder.init(arena);
|
var root = MapBuilder.init(arena);
|
||||||
var s = MapBuilder.init(arena);
|
var s = MapBuilder.init(arena);
|
||||||
try s.put("log_level", Node.str(@tagName(cfg.service.log_level)));
|
try s.put("log_level", Node.str(@tagName(cfg.service.log_level)));
|
||||||
try s.put("max_concurrent_jobs", Node.num(cfg.service.max_concurrent_jobs));
|
|
||||||
try s.put("heartbeat_interval_seconds", Node.num(cfg.service.heartbeat_interval_seconds));
|
try s.put("heartbeat_interval_seconds", Node.num(cfg.service.heartbeat_interval_seconds));
|
||||||
try s.put("ipc_socket", Node.str(socket));
|
try s.put("ipc_socket", Node.str(socket));
|
||||||
try s.put("stale_heartbeat_threshold_seconds", Node.num(cfg.service.stale_heartbeat_threshold_seconds));
|
try s.put("stale_heartbeat_threshold_seconds", Node.num(cfg.service.stale_heartbeat_threshold_seconds));
|
||||||
@@ -588,11 +590,9 @@ fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8) !Node {
|
|||||||
try st.put("preserve_work_dir", .{ .boolean = cfg.storage.preserve_work_dir });
|
try st.put("preserve_work_dir", .{ .boolean = cfg.storage.preserve_work_dir });
|
||||||
try root.put("storage", try st.done());
|
try root.put("storage", try st.done());
|
||||||
|
|
||||||
var l = MapBuilder.init(arena);
|
if (warnings.len > 0) {
|
||||||
try l.put("max_high_jobs", Node.num(cfg.load_levels.max_high_jobs));
|
try root.put("warnings", .{ .list = try problemNodes(arena, warnings, true) });
|
||||||
try l.put("max_medium_jobs", Node.num(cfg.load_levels.max_medium_jobs));
|
}
|
||||||
try l.put("max_low_jobs", Node.num(cfg.load_levels.max_low_jobs));
|
|
||||||
try root.put("load_levels", try l.done());
|
|
||||||
return root.done();
|
return root.done();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -602,7 +602,7 @@ pub fn cmdConfigShow(ctx: *Context) !u8 {
|
|||||||
const socket = if (show_defaults) try (config.Config{}).ipcSocketPath(ctx.arena) else try cfg.ipcSocketPath(ctx.arena);
|
const socket = if (show_defaults) try (config.Config{}).ipcSocketPath(ctx.arena) else try cfg.ipcSocketPath(ctx.arena);
|
||||||
|
|
||||||
if (ctx.format != .human) {
|
if (ctx.format != .human) {
|
||||||
try ctx.emit(try configNode(ctx.arena, cfg, socket));
|
try ctx.emit(try configNode(ctx.arena, cfg, socket, ctx.config_deprecations.items));
|
||||||
return exit_ok;
|
return exit_ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -621,8 +621,8 @@ pub fn cmdConfigShow(ctx: *Context) !u8 {
|
|||||||
try w.print("Config file: {s}\n", .{try std.mem.join(ctx.arena, ", ", found.items)});
|
try w.print("Config file: {s}\n", .{try std.mem.join(ctx.arena, ", ", found.items)});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
try w.print("\n[service]\nlog_level = {s}\nmax_concurrent_jobs = {d}\nheartbeat_interval_seconds = {d}\nipc_socket = {s}\nstale_heartbeat_threshold_seconds = {d}\n", .{
|
try w.print("\n[service]\nlog_level = {s}\nheartbeat_interval_seconds = {d}\nipc_socket = {s}\nstale_heartbeat_threshold_seconds = {d}\n", .{
|
||||||
@tagName(cfg.service.log_level), cfg.service.max_concurrent_jobs, cfg.service.heartbeat_interval_seconds, socket, cfg.service.stale_heartbeat_threshold_seconds,
|
@tagName(cfg.service.log_level), cfg.service.heartbeat_interval_seconds, socket, cfg.service.stale_heartbeat_threshold_seconds,
|
||||||
});
|
});
|
||||||
try w.print("\n[jobs]\ndefault_timeout_seconds = {d}\nmax_retries = {d}\nretry_delay_seconds = {d}\nretry_backoff_multiplier = {d:.1}\nretry_on_exit_codes = [", .{
|
try w.print("\n[jobs]\ndefault_timeout_seconds = {d}\nmax_retries = {d}\nretry_delay_seconds = {d}\nretry_backoff_multiplier = {d:.1}\nretry_on_exit_codes = [", .{
|
||||||
cfg.jobs.default_timeout_seconds, cfg.jobs.max_retries, cfg.jobs.retry_delay_seconds, cfg.jobs.retry_backoff_multiplier,
|
cfg.jobs.default_timeout_seconds, cfg.jobs.max_retries, cfg.jobs.retry_delay_seconds, cfg.jobs.retry_backoff_multiplier,
|
||||||
@@ -635,9 +635,6 @@ pub fn cmdConfigShow(ctx: *Context) !u8 {
|
|||||||
try w.print("\n[storage]\nbase_dir = {s}\nmax_disk_usage_gb = {d}\npreserve_work_dir = {any}\n", .{
|
try w.print("\n[storage]\nbase_dir = {s}\nmax_disk_usage_gb = {d}\npreserve_work_dir = {any}\n", .{
|
||||||
cfg.storage.base_dir, cfg.storage.max_disk_usage_gb, cfg.storage.preserve_work_dir,
|
cfg.storage.base_dir, cfg.storage.max_disk_usage_gb, cfg.storage.preserve_work_dir,
|
||||||
});
|
});
|
||||||
try w.print("\n[load_levels]\nmax_high_jobs = {d}\nmax_medium_jobs = {d}\nmax_low_jobs = {d}\n", .{
|
|
||||||
cfg.load_levels.max_high_jobs, cfg.load_levels.max_medium_jobs, cfg.load_levels.max_low_jobs,
|
|
||||||
});
|
|
||||||
return exit_ok;
|
return exit_ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -647,6 +644,7 @@ pub const config_validate_usage =
|
|||||||
\\Usage: zag config validate --file <path>
|
\\Usage: zag config validate --file <path>
|
||||||
\\
|
\\
|
||||||
\\Check a configuration file for syntax errors, unknown sections or keys, and bad values.
|
\\Check a configuration file for syntax errors, unknown sections or keys, and bad values.
|
||||||
|
\\Deprecated settings are reported as warnings and do not affect the exit code.
|
||||||
\\Exits 1 if anything is wrong.
|
\\Exits 1 if anything is wrong.
|
||||||
\\
|
\\
|
||||||
\\Options:
|
\\Options:
|
||||||
@@ -676,38 +674,48 @@ pub fn cmdConfigValidate(ctx: *Context) !u8 {
|
|||||||
try list.append(a, .{ .section = "", .key = "", .message = try std.fmt.allocPrint(a, "Parse error at line {d}: {s}", .{ td.line, what }) });
|
try list.append(a, .{ .section = "", .key = "", .message = try std.fmt.allocPrint(a, "Parse error at line {d}: {s}", .{ td.line, what }) });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (list.items.len == 0) {
|
var error_count: usize = 0;
|
||||||
if (ctx.format == .human) {
|
for (list.items) |p| {
|
||||||
try ctx.stdout.print("Configuration is valid: {s}\n", .{path});
|
if (!p.is_warning) error_count += 1;
|
||||||
} else {
|
|
||||||
var m = MapBuilder.init(a);
|
|
||||||
try m.put("valid", .{ .boolean = true });
|
|
||||||
try m.put("file", Node.str(path));
|
|
||||||
try ctx.emit(try m.done());
|
|
||||||
}
|
|
||||||
return exit_ok;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (ctx.format == .human) {
|
if (ctx.format == .human) {
|
||||||
try ctx.stdout.print("Configuration errors in {s}:\n\n", .{path});
|
for (list.items) |p| if (p.is_warning) try ctx.stdout.print(" Warning: {s}\n", .{p.message});
|
||||||
for (list.items) |p| {
|
if (error_count == 0) {
|
||||||
if (p.key.len > 0) try ctx.stdout.print(" Key '{s}': {s}\n", .{ p.key, p.message }) else try ctx.stdout.print(" {s}\n", .{p.message});
|
try ctx.stdout.print("Configuration is valid: {s}\n", .{path});
|
||||||
|
} else {
|
||||||
|
try ctx.stdout.print("\nConfiguration errors in {s}:\n\n", .{path});
|
||||||
|
for (list.items) |p| {
|
||||||
|
if (p.is_warning) continue;
|
||||||
|
if (p.key.len > 0) try ctx.stdout.print(" Key '{s}': {s}\n", .{ p.key, p.message }) else try ctx.stdout.print(" {s}\n", .{p.message});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const nodes = try a.alloc(Node, list.items.len);
|
const warnings = try problemNodes(a, list.items, true);
|
||||||
for (list.items, nodes) |p, *n| {
|
const errors = try problemNodes(a, list.items, false);
|
||||||
var em = MapBuilder.init(a);
|
|
||||||
if (p.key.len > 0) try em.put("key", Node.str(p.key));
|
|
||||||
try em.put("message", Node.str(p.message));
|
|
||||||
n.* = try em.done();
|
|
||||||
}
|
|
||||||
var m = MapBuilder.init(a);
|
var m = MapBuilder.init(a);
|
||||||
try m.put("valid", .{ .boolean = false });
|
try m.put("valid", .{ .boolean = errors.len == 0 });
|
||||||
try m.put("file", Node.str(path));
|
try m.put("file", Node.str(path));
|
||||||
try m.put("errors", .{ .list = nodes });
|
if (warnings.len > 0) try m.put("warnings", .{ .list = warnings });
|
||||||
|
if (errors.len > 0) try m.put("errors", .{ .list = errors });
|
||||||
try ctx.emit(try m.done());
|
try ctx.emit(try m.done());
|
||||||
}
|
}
|
||||||
return exit_error;
|
return if (error_count == 0) exit_ok else exit_error;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The JSON node list for the warnings or the errors of a problem list: one
|
||||||
|
/// `{"key": ..., "message": ...}` object per problem (`key` omitted when empty).
|
||||||
|
/// `config show` and `config validate` render their deprecation warnings through this.
|
||||||
|
fn problemNodes(a: Allocator, list: []const config.Problem, warnings_only: bool) ![]Node {
|
||||||
|
var nodes: std.ArrayList(Node) = .empty;
|
||||||
|
for (list) |p| {
|
||||||
|
if (p.is_warning != warnings_only) continue;
|
||||||
|
var em = MapBuilder.init(a);
|
||||||
|
if (p.key.len > 0) try em.put("key", Node.str(p.key));
|
||||||
|
try em.put("message", Node.str(p.message));
|
||||||
|
try nodes.append(a, try em.done());
|
||||||
|
}
|
||||||
|
return nodes.toOwnedSlice(a);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn writeFileCreatingParents(ctx: *Context, path: []const u8, data: []const u8) !void {
|
fn writeFileCreatingParents(ctx: *Context, path: []const u8, data: []const u8) !void {
|
||||||
@@ -756,8 +764,7 @@ pub const config_install_opts = [_]args_mod.Opt{
|
|||||||
pub const config_install_usage =
|
pub const config_install_usage =
|
||||||
\\Usage: zag config install [options]
|
\\Usage: zag config install [options]
|
||||||
\\
|
\\
|
||||||
\\Install the default configuration files (zag.conf and the high/medium/low .load
|
\\Install the default configuration file (zag.conf) into the system config directory.
|
||||||
\\whitelists) into the system config directory.
|
|
||||||
\\
|
\\
|
||||||
\\Options:
|
\\Options:
|
||||||
\\ -d, --directory <dir> Target directory (default: /etc/zag)
|
\\ -d, --directory <dir> Target directory (default: /etc/zag)
|
||||||
@@ -824,7 +831,6 @@ const bash_completion =
|
|||||||
\\ case "$prev" in
|
\\ case "$prev" in
|
||||||
\\ -o|--output) COMPREPLY=( $(compgen -W "human json xml" -- "$cur") ); return ;;
|
\\ -o|--output) COMPREPLY=( $(compgen -W "human json xml" -- "$cur") ); return ;;
|
||||||
\\ -s|--state) COMPREPLY=( $(compgen -W "queued running succeeded failed canceled killed" -- "$cur") ); return ;;
|
\\ -s|--state) COMPREPLY=( $(compgen -W "queued running succeeded failed canceled killed" -- "$cur") ); return ;;
|
||||||
\\ -l|--load-level) COMPREPLY=( $(compgen -W "high medium low" -- "$cur") ); return ;;
|
|
||||||
\\ --config|--barn-dir|-d|--directory|-p|--path|-f|--file) COMPREPLY=( $(compgen -f -- "$cur") ); return ;;
|
\\ --config|--barn-dir|-d|--directory|-p|--path|-f|--file) COMPREPLY=( $(compgen -f -- "$cur") ); return ;;
|
||||||
\\ esac
|
\\ esac
|
||||||
\\ if [[ -z "$cmd" ]]; then
|
\\ if [[ -z "$cmd" ]]; then
|
||||||
@@ -832,7 +838,7 @@ const bash_completion =
|
|||||||
\\ fi
|
\\ fi
|
||||||
\\ local opts="$global"
|
\\ local opts="$global"
|
||||||
\\ case "$cmd" in
|
\\ case "$cmd" in
|
||||||
\\ run) opts="$opts -t --tag -l --load-level --max-retries --retry-delay --timeout" ;;
|
\\ run) opts="$opts -t --tag --max-retries --retry-delay --timeout" ;;
|
||||||
\\ status) opts="$opts -t --tag -s --state -n --limit" ;;
|
\\ status) opts="$opts -t --tag -s --state -n --limit" ;;
|
||||||
\\ describe) opts="$opts --logs --manifest" ;;
|
\\ describe) opts="$opts --logs --manifest" ;;
|
||||||
\\ usage) opts="$opts -n --limit --csv --summary" ;;
|
\\ usage) opts="$opts -n --limit --csv --summary" ;;
|
||||||
|
|||||||
+2
-18
@@ -10,7 +10,6 @@ const Node = output.Node;
|
|||||||
const MapBuilder = output.MapBuilder;
|
const MapBuilder = output.MapBuilder;
|
||||||
const jsonpretty = @import("jsonpretty.zig");
|
const jsonpretty = @import("jsonpretty.zig");
|
||||||
const jobjson = @import("jobjson.zig");
|
const jobjson = @import("jobjson.zig");
|
||||||
const config = @import("config.zig");
|
|
||||||
const dirs_mod = @import("dirs.zig");
|
const dirs_mod = @import("dirs.zig");
|
||||||
const Dirs = dirs_mod.Dirs;
|
const Dirs = dirs_mod.Dirs;
|
||||||
const Repository = @import("repository.zig").Repository;
|
const Repository = @import("repository.zig").Repository;
|
||||||
@@ -23,8 +22,6 @@ const duration = @import("duration.zig");
|
|||||||
const timestamp = @import("timestamp.zig");
|
const timestamp = @import("timestamp.zig");
|
||||||
const proc = @import("proc.zig");
|
const proc = @import("proc.zig");
|
||||||
const state_mod = @import("state.zig");
|
const state_mod = @import("state.zig");
|
||||||
const LoadLevel = @import("loadlevel.zig").LoadLevel;
|
|
||||||
const Classifier = @import("loadclass.zig").Classifier;
|
|
||||||
const Job = @import("job.zig").Job;
|
const Job = @import("job.zig").Job;
|
||||||
const Instant = @import("job.zig").Instant;
|
const Instant = @import("job.zig").Instant;
|
||||||
|
|
||||||
@@ -113,7 +110,6 @@ fn summaryNode(arena: Allocator, jobs: []const Job) !Node {
|
|||||||
|
|
||||||
pub const run_opts = [_]args_mod.Opt{
|
pub const run_opts = [_]args_mod.Opt{
|
||||||
.{ .long = "tag", .short = 't', .takes_value = true },
|
.{ .long = "tag", .short = 't', .takes_value = true },
|
||||||
.{ .long = "load-level", .short = 'l', .takes_value = true },
|
|
||||||
.{ .long = "max-retries", .takes_value = true },
|
.{ .long = "max-retries", .takes_value = true },
|
||||||
.{ .long = "retry-delay", .takes_value = true },
|
.{ .long = "retry-delay", .takes_value = true },
|
||||||
.{ .long = "timeout", .takes_value = true },
|
.{ .long = "timeout", .takes_value = true },
|
||||||
@@ -127,7 +123,6 @@ pub const run_usage =
|
|||||||
\\
|
\\
|
||||||
\\Options:
|
\\Options:
|
||||||
\\ -t, --tag <string> Tag for filtering jobs
|
\\ -t, --tag <string> Tag for filtering jobs
|
||||||
\\ -l, --load-level <level> high, medium or low (default: auto-detect)
|
|
||||||
\\ --max-retries <n> Override the maximum number of retries
|
\\ --max-retries <n> Override the maximum number of retries
|
||||||
\\ --retry-delay <secs> Override the initial retry delay
|
\\ --retry-delay <secs> Override the initial retry delay
|
||||||
\\ --timeout <secs> Kill the job after this many seconds
|
\\ --timeout <secs> Kill the job after this many seconds
|
||||||
@@ -141,9 +136,6 @@ pub fn cmdRun(ctx: *Context) !u8 {
|
|||||||
const command = ctx.parsed.positionals;
|
const command = ctx.parsed.positionals;
|
||||||
if (command.len == 0) return ctx.usageError("No command specified", .{});
|
if (command.len == 0) return ctx.usageError("No command specified", .{});
|
||||||
|
|
||||||
var load_level: ?LoadLevel = null;
|
|
||||||
if (ctx.value("load-level")) |l| load_level = LoadLevel.parse(l) orelse
|
|
||||||
return ctx.usageError("Invalid load level '{s}'. Valid values are: high, medium, low", .{l});
|
|
||||||
var max_retries: ?u32 = null;
|
var max_retries: ?u32 = null;
|
||||||
if (ctx.value("max-retries")) |v| max_retries = parseCount(v) orelse return ctx.usageError("Invalid --max-retries '{s}'", .{v});
|
if (ctx.value("max-retries")) |v| max_retries = parseCount(v) orelse return ctx.usageError("Invalid --max-retries '{s}'", .{v});
|
||||||
var retry_delay: ?u32 = null;
|
var retry_delay: ?u32 = null;
|
||||||
@@ -154,7 +146,7 @@ pub fn cmdRun(ctx: *Context) !u8 {
|
|||||||
|
|
||||||
var job: Job = undefined;
|
var job: Job = undefined;
|
||||||
if (ctx.flag("offline")) {
|
if (ctx.flag("offline")) {
|
||||||
job = (try runOffline(ctx, command, load_level, max_retries, retry_delay, timeout)) orelse return exit_error;
|
job = (try runOffline(ctx, command, max_retries, retry_delay, timeout)) orelse return exit_error;
|
||||||
} else {
|
} else {
|
||||||
var p: Payload = undefined;
|
var p: Payload = undefined;
|
||||||
p.init(ctx.arena);
|
p.init(ctx.arena);
|
||||||
@@ -164,7 +156,6 @@ pub fn cmdRun(ctx: *Context) !u8 {
|
|||||||
for (command) |c| try p.w.string(c);
|
for (command) |c| try p.w.string(c);
|
||||||
try p.w.endArray();
|
try p.w.endArray();
|
||||||
if (ctx.value("tag")) |t| try p.w.field("tag", .string, t);
|
if (ctx.value("tag")) |t| try p.w.field("tag", .string, t);
|
||||||
if (load_level) |l| try p.w.field("loadLevel", .string, l.upper());
|
|
||||||
if (max_retries) |n| try p.w.field("maxRetries", .int, n);
|
if (max_retries) |n| try p.w.field("maxRetries", .int, n);
|
||||||
if (retry_delay) |n| try p.w.field("retryDelaySeconds", .int, n);
|
if (retry_delay) |n| try p.w.field("retryDelaySeconds", .int, n);
|
||||||
if (timeout) |n| try p.w.field("timeoutSeconds", .int, n);
|
if (timeout) |n| try p.w.field("timeoutSeconds", .int, n);
|
||||||
@@ -186,17 +177,14 @@ pub fn cmdRun(ctx: *Context) !u8 {
|
|||||||
return exit_ok;
|
return exit_ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
fn runOffline(ctx: *Context, command: []const []const u8, load_level: ?LoadLevel, max_retries: ?u32, retry_delay: ?u32, timeout: ?u32) !?Job {
|
fn runOffline(ctx: *Context, command: []const []const u8, max_retries: ?u32, retry_delay: ?u32, timeout: ?u32) !?Job {
|
||||||
var dirs = try ctx.openDirs();
|
var dirs = try ctx.openDirs();
|
||||||
defer dirs.close(ctx.io);
|
defer dirs.close(ctx.io);
|
||||||
const repo = Repository.init(ctx.io, &dirs);
|
const repo = Repository.init(ctx.io, &dirs);
|
||||||
const cfg = ctx.configOrDefault();
|
const cfg = ctx.configOrDefault();
|
||||||
|
|
||||||
const sys_dir = try config.systemConfigDir(ctx.arena, ctx.env);
|
|
||||||
const classifier = try Classifier.loadOrDefaults(ctx.arena, ctx.io, sys_dir);
|
|
||||||
const created = try repo.create(ctx.arena, command, .{
|
const created = try repo.create(ctx.arena, command, .{
|
||||||
.tag = ctx.value("tag"),
|
.tag = ctx.value("tag"),
|
||||||
.load_level = load_level orelse classifier.classify(command),
|
|
||||||
.max_retries = max_retries orelse cfg.jobs.max_retries,
|
.max_retries = max_retries orelse cfg.jobs.max_retries,
|
||||||
.retry_delay_seconds = retry_delay orelse cfg.jobs.retry_delay_seconds,
|
.retry_delay_seconds = retry_delay orelse cfg.jobs.retry_delay_seconds,
|
||||||
.retry_backoff_multiplier = cfg.jobs.retry_backoff_multiplier,
|
.retry_backoff_multiplier = cfg.jobs.retry_backoff_multiplier,
|
||||||
@@ -308,8 +296,6 @@ fn printStatusTable(ctx: *Context, jobs: []const Job) !void {
|
|||||||
try w.writeAll(sep);
|
try w.writeAll(sep);
|
||||||
try pad(w, "STATE", 9);
|
try pad(w, "STATE", 9);
|
||||||
try w.writeAll(sep);
|
try w.writeAll(sep);
|
||||||
try pad(w, "LOAD", 6);
|
|
||||||
try w.writeAll(sep);
|
|
||||||
try pad(w, "TAG", tag_w);
|
try pad(w, "TAG", tag_w);
|
||||||
try w.writeAll(sep);
|
try w.writeAll(sep);
|
||||||
try pad(w, "CREATED", 19);
|
try pad(w, "CREATED", 19);
|
||||||
@@ -327,8 +313,6 @@ fn printStatusTable(ctx: *Context, jobs: []const Job) !void {
|
|||||||
try w.writeAll(sep);
|
try w.writeAll(sep);
|
||||||
try colorCell(ctx, j.state.lower(), 9, stateStyle(j.state));
|
try colorCell(ctx, j.state.lower(), 9, stateStyle(j.state));
|
||||||
try w.writeAll(sep);
|
try w.writeAll(sep);
|
||||||
try pad(w, j.load_level.lower(), 6);
|
|
||||||
try w.writeAll(sep);
|
|
||||||
try pad(w, j.tag orelse "-", tag_w);
|
try pad(w, j.tag orelse "-", tag_w);
|
||||||
try w.writeAll(sep);
|
try w.writeAll(sep);
|
||||||
try pad(w, fmtTime(a, j.created_at), 19);
|
try pad(w, fmtTime(a, j.created_at), 19);
|
||||||
|
|||||||
+205
-59
@@ -19,20 +19,12 @@ pub const LogLevel = enum {
|
|||||||
|
|
||||||
pub const Service = struct {
|
pub const Service = struct {
|
||||||
log_level: LogLevel = .info,
|
log_level: LogLevel = .info,
|
||||||
/// Deprecated: superseded by `[load_levels]`.
|
|
||||||
max_concurrent_jobs: u32 = 4,
|
|
||||||
heartbeat_interval_seconds: u32 = 5,
|
heartbeat_interval_seconds: u32 = 5,
|
||||||
/// Defaults to `<storage.base_dir>/zag.sock` when unset.
|
/// Defaults to `<storage.base_dir>/zag.sock` when unset.
|
||||||
ipc_socket: ?[]const u8 = null,
|
ipc_socket: ?[]const u8 = null,
|
||||||
stale_heartbeat_threshold_seconds: u32 = 30,
|
stale_heartbeat_threshold_seconds: u32 = 30,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const LoadLevels = struct {
|
|
||||||
max_high_jobs: u32 = 2,
|
|
||||||
max_medium_jobs: u32 = 8,
|
|
||||||
max_low_jobs: u32 = 32,
|
|
||||||
};
|
|
||||||
|
|
||||||
pub const Jobs = struct {
|
pub const Jobs = struct {
|
||||||
default_timeout_seconds: u32 = 3600,
|
default_timeout_seconds: u32 = 3600,
|
||||||
max_retries: u32 = 3,
|
max_retries: u32 = 3,
|
||||||
@@ -63,7 +55,6 @@ pub const Config = struct {
|
|||||||
jobs: Jobs = .{},
|
jobs: Jobs = .{},
|
||||||
cleanup: Cleanup = .{},
|
cleanup: Cleanup = .{},
|
||||||
storage: Storage = .{},
|
storage: Storage = .{},
|
||||||
load_levels: LoadLevels = .{},
|
|
||||||
|
|
||||||
/// Socket path: explicit `service.ipc_socket`, else `<base_dir>/zag.sock`.
|
/// Socket path: explicit `service.ipc_socket`, else `<base_dir>/zag.sock`.
|
||||||
pub fn ipcSocketPath(self: Config, arena: Allocator) ![]const u8 {
|
pub fn ipcSocketPath(self: Config, arena: Allocator) ![]const u8 {
|
||||||
@@ -75,10 +66,6 @@ pub const Config = struct {
|
|||||||
const checks = .{
|
const checks = .{
|
||||||
.{ "service", "heartbeat_interval_seconds", self.service.heartbeat_interval_seconds, 1 },
|
.{ "service", "heartbeat_interval_seconds", self.service.heartbeat_interval_seconds, 1 },
|
||||||
.{ "service", "stale_heartbeat_threshold_seconds", self.service.stale_heartbeat_threshold_seconds, 1 },
|
.{ "service", "stale_heartbeat_threshold_seconds", self.service.stale_heartbeat_threshold_seconds, 1 },
|
||||||
.{ "service", "max_concurrent_jobs", self.service.max_concurrent_jobs, 1 },
|
|
||||||
.{ "load_levels", "max_high_jobs", self.load_levels.max_high_jobs, 1 },
|
|
||||||
.{ "load_levels", "max_medium_jobs", self.load_levels.max_medium_jobs, 1 },
|
|
||||||
.{ "load_levels", "max_low_jobs", self.load_levels.max_low_jobs, 1 },
|
|
||||||
.{ "jobs", "default_timeout_seconds", self.jobs.default_timeout_seconds, 1 },
|
.{ "jobs", "default_timeout_seconds", self.jobs.default_timeout_seconds, 1 },
|
||||||
.{ "cleanup", "max_age_hours", self.cleanup.max_age_hours, 1 },
|
.{ "cleanup", "max_age_hours", self.cleanup.max_age_hours, 1 },
|
||||||
.{ "cleanup", "cleanup_interval_minutes", self.cleanup.cleanup_interval_minutes, 1 },
|
.{ "cleanup", "cleanup_interval_minutes", self.cleanup.cleanup_interval_minutes, 1 },
|
||||||
@@ -172,14 +159,22 @@ fn applySection(arena: Allocator, comptime T: type, name: []const u8, section: ?
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The sections zag's config understands, in declaration order. `fromDoc` builds the config
|
||||||
|
/// from these and `checkDoc` validates them, so a section added here is applied and checked
|
||||||
|
/// in one go.
|
||||||
|
const sections = [_]struct { name: []const u8, ty: type }{
|
||||||
|
.{ .name = "service", .ty = Service },
|
||||||
|
.{ .name = "jobs", .ty = Jobs },
|
||||||
|
.{ .name = "cleanup", .ty = Cleanup },
|
||||||
|
.{ .name = "storage", .ty = Storage },
|
||||||
|
};
|
||||||
|
|
||||||
/// Builds a `Config` from a merged TOML document (unknown sections/keys are ignored).
|
/// Builds a `Config` from a merged TOML document (unknown sections/keys are ignored).
|
||||||
pub fn fromDoc(arena: Allocator, doc: toml.Doc, diag: ?*Diagnostic) Error!Config {
|
pub fn fromDoc(arena: Allocator, doc: toml.Doc, diag: ?*Diagnostic) Error!Config {
|
||||||
var cfg: Config = .{};
|
var cfg: Config = .{};
|
||||||
try applySection(arena, Service, "service", doc.get("service"), &cfg.service, diag);
|
inline for (sections) |sec| {
|
||||||
try applySection(arena, Jobs, "jobs", doc.get("jobs"), &cfg.jobs, diag);
|
try applySection(arena, sec.ty, sec.name, doc.get(sec.name), &@field(cfg, sec.name), diag);
|
||||||
try applySection(arena, Cleanup, "cleanup", doc.get("cleanup"), &cfg.cleanup, diag);
|
}
|
||||||
try applySection(arena, Storage, "storage", doc.get("storage"), &cfg.storage, diag);
|
|
||||||
try applySection(arena, LoadLevels, "load_levels", doc.get("load_levels"), &cfg.load_levels, diag);
|
|
||||||
try cfg.validate(diag);
|
try cfg.validate(diag);
|
||||||
return cfg;
|
return cfg;
|
||||||
}
|
}
|
||||||
@@ -191,10 +186,10 @@ pub const Problem = struct {
|
|||||||
/// Empty for problems that concern a whole section.
|
/// Empty for problems that concern a whole section.
|
||||||
key: []const u8,
|
key: []const u8,
|
||||||
message: []const u8,
|
message: []const u8,
|
||||||
|
/// Non-fatal notice (a deprecated setting); never fails validation.
|
||||||
|
is_warning: bool = false,
|
||||||
};
|
};
|
||||||
|
|
||||||
const known_sections = [_][]const u8{ "service", "jobs", "cleanup", "storage", "load_levels" };
|
|
||||||
|
|
||||||
fn expectation(comptime T: type) []const u8 {
|
fn expectation(comptime T: type) []const u8 {
|
||||||
return switch (@typeInfo(T)) {
|
return switch (@typeInfo(T)) {
|
||||||
.optional => |o| expectation(o.child),
|
.optional => |o| expectation(o.child),
|
||||||
@@ -229,32 +224,73 @@ fn checkSection(arena: Allocator, comptime T: type, name: []const u8, section: t
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (!known) {
|
if (!known) {
|
||||||
try out.append(arena, .{
|
// A key barn (and pre-flattening zag) configs still carry: report it as a
|
||||||
.section = name,
|
// warning and keep loading; extend this check when the next setting is removed.
|
||||||
.key = key,
|
if (std.mem.eql(u8, name, "service") and std.mem.eql(u8, key, "max_concurrent_jobs")) {
|
||||||
.message = try std.fmt.allocPrint(arena, "Unknown key '{s}' in [{s}] section", .{ key, name }),
|
try out.append(arena, .{
|
||||||
});
|
.section = name,
|
||||||
|
.key = key,
|
||||||
|
.message = try std.fmt.allocPrint(arena, "'{s}' is deprecated: only one job runs at a time; remove it from your config", .{key}),
|
||||||
|
.is_warning = true,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
try out.append(arena, .{
|
||||||
|
.section = name,
|
||||||
|
.key = key,
|
||||||
|
.message = try std.fmt.allocPrint(arena, "Unknown key '{s}' in [{s}] section", .{ key, name }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Unknown sections and keys, values of the wrong type, and deprecated settings (reported as
|
||||||
|
/// warnings) in a parsed document. Range violations are not checked here; see `problems`.
|
||||||
|
fn checkDoc(arena: Allocator, doc: toml.Doc, out: *std.ArrayList(Problem)) Allocator.Error!void {
|
||||||
|
var it = doc.iterator();
|
||||||
|
while (it.next()) |entry| {
|
||||||
|
const name = entry.key_ptr.*;
|
||||||
|
const section = entry.value_ptr.*;
|
||||||
|
var known = false;
|
||||||
|
inline for (sections) |sec| {
|
||||||
|
if (std.mem.eql(u8, name, sec.name)) {
|
||||||
|
known = true;
|
||||||
|
try checkSection(arena, sec.ty, name, section, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!known) {
|
||||||
|
// Kept for compatibility with pre-flattening (and barn) configs.
|
||||||
|
if (std.mem.eql(u8, name, "load_levels")) {
|
||||||
|
try out.append(arena, .{
|
||||||
|
.section = name,
|
||||||
|
.key = "",
|
||||||
|
.message = try std.fmt.allocPrint(arena, "[{s}] is deprecated: only one job runs at a time; remove it from your config", .{name}),
|
||||||
|
.is_warning = true,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
try out.append(arena, .{
|
||||||
|
.section = name,
|
||||||
|
.key = "",
|
||||||
|
.message = try std.fmt.allocPrint(arena, "Unknown section: [{s}]", .{name}),
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Everything wrong with a parsed config document: unknown sections and keys, values of the
|
/// Everything wrong with a parsed config document: unknown sections and keys, values of the
|
||||||
/// wrong type, and values outside their allowed range.
|
/// wrong type, and values outside their allowed range. Deprecated settings are reported as
|
||||||
|
/// warnings and never fail validation.
|
||||||
pub fn problems(arena: Allocator, doc: toml.Doc) Allocator.Error![]const Problem {
|
pub fn problems(arena: Allocator, doc: toml.Doc) Allocator.Error![]const Problem {
|
||||||
var out: std.ArrayList(Problem) = .empty;
|
var out: std.ArrayList(Problem) = .empty;
|
||||||
var it = doc.iterator();
|
try checkDoc(arena, doc, &out);
|
||||||
while (it.next()) |entry| {
|
// Warnings are not errors: a deprecated setting must not suppress the range check
|
||||||
const name = entry.key_ptr.*;
|
// (nor the "valid" verdict) for the rest of the document.
|
||||||
const section = entry.value_ptr.*;
|
var error_count: usize = 0;
|
||||||
if (std.mem.eql(u8, name, "service")) try checkSection(arena, Service, name, section, &out) else if (std.mem.eql(u8, name, "jobs")) try checkSection(arena, Jobs, name, section, &out) else if (std.mem.eql(u8, name, "cleanup")) try checkSection(arena, Cleanup, name, section, &out) else if (std.mem.eql(u8, name, "storage")) try checkSection(arena, Storage, name, section, &out) else if (std.mem.eql(u8, name, "load_levels")) try checkSection(arena, LoadLevels, name, section, &out) else {
|
for (out.items) |p| {
|
||||||
try out.append(arena, .{
|
if (!p.is_warning) error_count += 1;
|
||||||
.section = name,
|
|
||||||
.key = "",
|
|
||||||
.message = try std.fmt.allocPrint(arena, "Unknown section: [{s}]", .{name}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (out.items.len == 0) {
|
if (error_count == 0) {
|
||||||
// Types are fine; now check ranges on the resulting configuration.
|
// Types are fine; now check ranges on the resulting configuration.
|
||||||
var diag: Diagnostic = .{};
|
var diag: Diagnostic = .{};
|
||||||
_ = fromDoc(arena, doc, &diag) catch |err| switch (err) {
|
_ = fromDoc(arena, doc, &diag) catch |err| switch (err) {
|
||||||
@@ -287,20 +323,41 @@ pub fn mergeInto(arena: Allocator, dst: *toml.Doc, src: toml.Doc) Allocator.Erro
|
|||||||
|
|
||||||
const env_prefix = "ZAG_";
|
const env_prefix = "ZAG_";
|
||||||
const env_sections = [_]struct { name: []const u8, canonical: []const u8 }{
|
const env_sections = [_]struct { name: []const u8, canonical: []const u8 }{
|
||||||
.{ .name = "load_levels", .canonical = "load_levels" },
|
|
||||||
.{ .name = "loadlevels", .canonical = "load_levels" },
|
|
||||||
.{ .name = "service", .canonical = "service" },
|
.{ .name = "service", .canonical = "service" },
|
||||||
.{ .name = "jobs", .canonical = "jobs" },
|
.{ .name = "jobs", .canonical = "jobs" },
|
||||||
.{ .name = "cleanup", .canonical = "cleanup" },
|
.{ .name = "cleanup", .canonical = "cleanup" },
|
||||||
.{ .name = "storage", .canonical = "storage" },
|
.{ .name = "storage", .canonical = "storage" },
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Applies `ZAG_<SECTION>_<KEY>=value` overrides, e.g. `ZAG_JOBS_MAX_RETRIES=5` or
|
/// `ZAG_LOAD_LEVELS_*`, `ZAG_LOADLEVELS_*` and `ZAG_SERVICE_MAX_CONCURRENT_JOBS` still
|
||||||
/// `ZAG_LOAD_LEVELS_MAX_HIGH_JOBS=1`. Values are typed as bool, int, float, else string.
|
/// survive in old service files and shell profiles; `rest` is the name without `ZAG_`.
|
||||||
pub fn applyEnvironment(arena: Allocator, doc: *toml.Doc, env: *const Environ.Map) Allocator.Error!void {
|
fn isDeprecatedEnvName(rest: []const u8) bool {
|
||||||
|
// The `len >` guards (rather than `>=`) keep the bare prefixes `ZAG_LOAD_LEVELS_` and
|
||||||
|
// `ZAG_LOADLEVELS_` from matching: they name no setting, mirroring how `env_sections`
|
||||||
|
// requires at least one character after the section underscore.
|
||||||
|
return (rest.len > "load_levels_".len and std.ascii.startsWithIgnoreCase(rest, "load_levels_")) or
|
||||||
|
(rest.len > "loadlevels_".len and std.ascii.startsWithIgnoreCase(rest, "loadlevels_")) or
|
||||||
|
std.ascii.eqlIgnoreCase(rest, "service_max_concurrent_jobs");
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies `ZAG_<SECTION>_<KEY>=value` overrides, e.g. `ZAG_JOBS_MAX_RETRIES=5`. Values are
|
||||||
|
/// typed as bool, int, float, else string. Deprecated load-level variables are skipped and,
|
||||||
|
/// when `deprecations` is non-null, reported there.
|
||||||
|
pub fn applyEnvironment(arena: Allocator, doc: *toml.Doc, env: *const Environ.Map, deprecations: ?*std.ArrayList(Problem)) Allocator.Error!void {
|
||||||
for (env.keys(), env.values()) |name, value| {
|
for (env.keys(), env.values()) |name, value| {
|
||||||
if (!std.ascii.startsWithIgnoreCase(name, env_prefix)) continue;
|
if (!std.ascii.startsWithIgnoreCase(name, env_prefix)) continue;
|
||||||
const rest = name[env_prefix.len..];
|
const rest = name[env_prefix.len..];
|
||||||
|
if (isDeprecatedEnvName(rest)) {
|
||||||
|
if (deprecations) |list| {
|
||||||
|
try list.append(arena, .{
|
||||||
|
.section = "",
|
||||||
|
.key = name,
|
||||||
|
.message = try std.fmt.allocPrint(arena, "{s} is deprecated: only one job runs at a time; remove it from your environment", .{name}),
|
||||||
|
.is_warning = true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
for (env_sections) |sec| {
|
for (env_sections) |sec| {
|
||||||
if (rest.len <= sec.name.len + 1) continue;
|
if (rest.len <= sec.name.len + 1) continue;
|
||||||
if (!std.ascii.eqlIgnoreCase(rest[0..sec.name.len], sec.name) or rest[sec.name.len] != '_') continue;
|
if (!std.ascii.eqlIgnoreCase(rest[0..sec.name.len], sec.name) or rest[sec.name.len] != '_') continue;
|
||||||
@@ -389,8 +446,10 @@ pub const LoadOptions = struct {
|
|||||||
};
|
};
|
||||||
|
|
||||||
/// Loads the effective configuration. Unreadable or malformed *implicit* files (system/user)
|
/// Loads the effective configuration. Unreadable or malformed *implicit* files (system/user)
|
||||||
/// are skipped like barn does; an explicit file that fails to parse is reported.
|
/// are skipped like barn does; an explicit file that fails to parse is reported. When
|
||||||
pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions, diag: ?*Diagnostic) Error!Config {
|
/// `deprecations` is non-null, removed settings found in the files or the environment are
|
||||||
|
/// appended to it as warnings.
|
||||||
|
pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions, diag: ?*Diagnostic, deprecations: ?*std.ArrayList(Problem)) Error!Config {
|
||||||
var merged: toml.Doc = .empty;
|
var merged: toml.Doc = .empty;
|
||||||
const paths = opts.search_paths orelse try searchPaths(arena, env);
|
const paths = opts.search_paths orelse try searchPaths(arena, env);
|
||||||
for (paths) |p| {
|
for (paths) |p| {
|
||||||
@@ -403,7 +462,15 @@ pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions
|
|||||||
if (opts.explicit_path) |p| {
|
if (opts.explicit_path) |p| {
|
||||||
if (try loadFile(arena, io, p, diag)) |d| try mergeInto(arena, &merged, d);
|
if (try loadFile(arena, io, p, diag)) |d| try mergeInto(arena, &merged, d);
|
||||||
}
|
}
|
||||||
try applyEnvironment(arena, &merged, env);
|
try applyEnvironment(arena, &merged, env, deprecations);
|
||||||
|
if (deprecations) |list| {
|
||||||
|
// Only the deprecation warnings come from the document scan (unknown names are
|
||||||
|
// ignored here, like barn), and `fromDoc` below does the range check; skip
|
||||||
|
// `problems()` and its extra pass over the document.
|
||||||
|
var found: std.ArrayList(Problem) = .empty;
|
||||||
|
try checkDoc(arena, merged, &found);
|
||||||
|
for (found.items) |p| if (p.is_warning) try list.append(arena, p);
|
||||||
|
}
|
||||||
return fromDoc(arena, merged, diag);
|
return fromDoc(arena, merged, diag);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -420,9 +487,6 @@ test "defaults match barn" {
|
|||||||
try std.testing.expectEqual(LogLevel.info, cfg.service.log_level);
|
try std.testing.expectEqual(LogLevel.info, cfg.service.log_level);
|
||||||
try std.testing.expectEqual(@as(u32, 5), cfg.service.heartbeat_interval_seconds);
|
try std.testing.expectEqual(@as(u32, 5), cfg.service.heartbeat_interval_seconds);
|
||||||
try std.testing.expectEqual(@as(u32, 30), cfg.service.stale_heartbeat_threshold_seconds);
|
try std.testing.expectEqual(@as(u32, 30), cfg.service.stale_heartbeat_threshold_seconds);
|
||||||
try std.testing.expectEqual(@as(u32, 2), cfg.load_levels.max_high_jobs);
|
|
||||||
try std.testing.expectEqual(@as(u32, 8), cfg.load_levels.max_medium_jobs);
|
|
||||||
try std.testing.expectEqual(@as(u32, 32), cfg.load_levels.max_low_jobs);
|
|
||||||
try std.testing.expectEqual(@as(u32, 3600), cfg.jobs.default_timeout_seconds);
|
try std.testing.expectEqual(@as(u32, 3600), cfg.jobs.default_timeout_seconds);
|
||||||
try std.testing.expectEqual(@as(u32, 3), cfg.jobs.max_retries);
|
try std.testing.expectEqual(@as(u32, 3), cfg.jobs.max_retries);
|
||||||
try std.testing.expectEqual(@as(f64, 2.0), cfg.jobs.retry_backoff_multiplier);
|
try std.testing.expectEqual(@as(f64, 2.0), cfg.jobs.retry_backoff_multiplier);
|
||||||
@@ -439,7 +503,6 @@ test "embedded default zag.conf parses to the built-in defaults" {
|
|||||||
const defaults = @import("defaults.zig");
|
const defaults = @import("defaults.zig");
|
||||||
const cfg = try fromDoc(arena.allocator(), try testDoc(arena.allocator(), defaults.zag_conf), null);
|
const cfg = try fromDoc(arena.allocator(), try testDoc(arena.allocator(), defaults.zag_conf), null);
|
||||||
try std.testing.expectEqual((Config{}).jobs.max_retries, cfg.jobs.max_retries);
|
try std.testing.expectEqual((Config{}).jobs.max_retries, cfg.jobs.max_retries);
|
||||||
try std.testing.expectEqual((Config{}).load_levels, cfg.load_levels);
|
|
||||||
try std.testing.expectEqual((Config{}).cleanup, cfg.cleanup);
|
try std.testing.expectEqual((Config{}).cleanup, cfg.cleanup);
|
||||||
try std.testing.expectEqual(@as(usize, 0), cfg.jobs.retry_on_exit_codes.len);
|
try std.testing.expectEqual(@as(usize, 0), cfg.jobs.retry_on_exit_codes.len);
|
||||||
try std.testing.expectEqualStrings("/tmp/zag", cfg.storage.base_dir);
|
try std.testing.expectEqualStrings("/tmp/zag", cfg.storage.base_dir);
|
||||||
@@ -479,8 +542,6 @@ test "validation rejects bad values and names the key" {
|
|||||||
const a = arena.allocator();
|
const a = arena.allocator();
|
||||||
var diag: Diagnostic = .{};
|
var diag: Diagnostic = .{};
|
||||||
|
|
||||||
try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[load_levels]\nmax_high_jobs = 0\n"), &diag));
|
|
||||||
try std.testing.expectEqualStrings("max_high_jobs", diag.key);
|
|
||||||
try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[jobs]\nretry_backoff_multiplier = 0.5\n"), &diag));
|
try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[jobs]\nretry_backoff_multiplier = 0.5\n"), &diag));
|
||||||
try std.testing.expectEqualStrings("retry_backoff_multiplier", diag.key);
|
try std.testing.expectEqualStrings("retry_backoff_multiplier", diag.key);
|
||||||
try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[service]\nlog_level = \"loud\"\n"), &diag));
|
try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[service]\nlog_level = \"loud\"\n"), &diag));
|
||||||
@@ -489,7 +550,7 @@ test "validation rejects bad values and names the key" {
|
|||||||
try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[cleanup]\nenabled = 5\n"), &diag));
|
try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[cleanup]\nenabled = 5\n"), &diag));
|
||||||
}
|
}
|
||||||
|
|
||||||
test "environment overrides, including load_levels" {
|
test "environment overrides; deprecated load-level vars are warned about and ignored" {
|
||||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||||
defer arena.deinit();
|
defer arena.deinit();
|
||||||
const a = arena.allocator();
|
const a = arena.allocator();
|
||||||
@@ -498,6 +559,7 @@ test "environment overrides, including load_levels" {
|
|||||||
try env.put("ZAG_JOBS_MAX_RETRIES", "7");
|
try env.put("ZAG_JOBS_MAX_RETRIES", "7");
|
||||||
try env.put("ZAG_LOAD_LEVELS_MAX_HIGH_JOBS", "1");
|
try env.put("ZAG_LOAD_LEVELS_MAX_HIGH_JOBS", "1");
|
||||||
try env.put("ZAG_LOADLEVELS_MAX_LOW_JOBS", "4");
|
try env.put("ZAG_LOADLEVELS_MAX_LOW_JOBS", "4");
|
||||||
|
try env.put("ZAG_SERVICE_MAX_CONCURRENT_JOBS", "2");
|
||||||
try env.put("ZAG_CLEANUP_ENABLED", "false");
|
try env.put("ZAG_CLEANUP_ENABLED", "false");
|
||||||
try env.put("ZAG_SERVICE_LOG_LEVEL", "warn");
|
try env.put("ZAG_SERVICE_LOG_LEVEL", "warn");
|
||||||
try env.put("ZAG_JOBS_RETRY_BACKOFF_MULTIPLIER", "1.5");
|
try env.put("ZAG_JOBS_RETRY_BACKOFF_MULTIPLIER", "1.5");
|
||||||
@@ -505,11 +567,17 @@ test "environment overrides, including load_levels" {
|
|||||||
try env.put("OTHER_JOBS_MAX_RETRIES", "99");
|
try env.put("OTHER_JOBS_MAX_RETRIES", "99");
|
||||||
|
|
||||||
var doc = try testDoc(a, "[jobs]\nmax_retries = 2\n");
|
var doc = try testDoc(a, "[jobs]\nmax_retries = 2\n");
|
||||||
try applyEnvironment(a, &doc, &env);
|
var deprecations: std.ArrayList(Problem) = .empty;
|
||||||
|
try applyEnvironment(a, &doc, &env, &deprecations);
|
||||||
|
try std.testing.expectEqual(@as(usize, 3), deprecations.items.len);
|
||||||
|
for (deprecations.items) |p| {
|
||||||
|
try std.testing.expect(p.is_warning);
|
||||||
|
try std.testing.expect(std.mem.indexOf(u8, p.message, "deprecated") != null);
|
||||||
|
}
|
||||||
|
try std.testing.expect(doc.get("load_levels") == null);
|
||||||
|
|
||||||
const cfg = try fromDoc(a, doc, null);
|
const cfg = try fromDoc(a, doc, null);
|
||||||
try std.testing.expectEqual(@as(u32, 7), cfg.jobs.max_retries);
|
try std.testing.expectEqual(@as(u32, 7), cfg.jobs.max_retries);
|
||||||
try std.testing.expectEqual(@as(u32, 1), cfg.load_levels.max_high_jobs);
|
|
||||||
try std.testing.expectEqual(@as(u32, 4), cfg.load_levels.max_low_jobs);
|
|
||||||
try std.testing.expect(!cfg.cleanup.enabled);
|
try std.testing.expect(!cfg.cleanup.enabled);
|
||||||
try std.testing.expectEqual(LogLevel.warn, cfg.service.log_level);
|
try std.testing.expectEqual(LogLevel.warn, cfg.service.log_level);
|
||||||
try std.testing.expectEqual(@as(f64, 1.5), cfg.jobs.retry_backoff_multiplier);
|
try std.testing.expectEqual(@as(f64, 1.5), cfg.jobs.retry_backoff_multiplier);
|
||||||
@@ -542,7 +610,7 @@ test "files merge per key with explicit file and env on top" {
|
|||||||
const cfg = try load(a, io, &env, .{
|
const cfg = try load(a, io, &env, .{
|
||||||
.search_paths = &paths,
|
.search_paths = &paths,
|
||||||
.explicit_path = try std.fmt.allocPrint(a, "{s}/explicit.conf", .{base}),
|
.explicit_path = try std.fmt.allocPrint(a, "{s}/explicit.conf", .{base}),
|
||||||
}, null);
|
}, null, null);
|
||||||
try std.testing.expectEqual(@as(u32, 2), cfg.jobs.max_retries); // user beats system
|
try std.testing.expectEqual(@as(u32, 2), cfg.jobs.max_retries); // user beats system
|
||||||
try std.testing.expectEqual(@as(u32, 99), cfg.jobs.retry_delay_seconds); // env beats files
|
try std.testing.expectEqual(@as(u32, 99), cfg.jobs.retry_delay_seconds); // env beats files
|
||||||
try std.testing.expectEqual(@as(u32, 20), cfg.cleanup.max_age_hours); // explicit beats system
|
try std.testing.expectEqual(@as(u32, 20), cfg.cleanup.max_age_hours); // explicit beats system
|
||||||
@@ -551,7 +619,7 @@ test "files merge per key with explicit file and env on top" {
|
|||||||
try std.testing.expectError(error.ParseFailed, load(a, io, &env, .{
|
try std.testing.expectError(error.ParseFailed, load(a, io, &env, .{
|
||||||
.search_paths = &.{},
|
.search_paths = &.{},
|
||||||
.explicit_path = try std.fmt.allocPrint(a, "{s}/broken.conf", .{base}),
|
.explicit_path = try std.fmt.allocPrint(a, "{s}/broken.conf", .{base}),
|
||||||
}, &diag));
|
}, &diag, null));
|
||||||
try std.testing.expectEqual(@as(usize, 1), diag.line);
|
try std.testing.expectEqual(@as(usize, 1), diag.line);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -563,7 +631,11 @@ test "search paths point at zag.conf" {
|
|||||||
try env.put("HOME", "/home/dan");
|
try env.put("HOME", "/home/dan");
|
||||||
const paths = try searchPaths(arena.allocator(), &env);
|
const paths = try searchPaths(arena.allocator(), &env);
|
||||||
try std.testing.expectEqualStrings("/etc/zag/zag.conf", paths[0]);
|
try std.testing.expectEqualStrings("/etc/zag/zag.conf", paths[0]);
|
||||||
try std.testing.expectEqualStrings("/home/dan/.config/zag/zag.conf", paths[1]);
|
const user_path = switch (builtin.os.tag) {
|
||||||
|
.macos => "/home/dan/Library/Application Support/zag/zag.conf",
|
||||||
|
else => "/home/dan/.config/zag/zag.conf",
|
||||||
|
};
|
||||||
|
try std.testing.expectEqualStrings(user_path, paths[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
test "problems reports unknown names, bad types and ranges" {
|
test "problems reports unknown names, bad types and ranges" {
|
||||||
@@ -599,3 +671,77 @@ test "problems reports unknown names, bad types and ranges" {
|
|||||||
try std.testing.expectEqual(@as(usize, 1), range.len);
|
try std.testing.expectEqual(@as(usize, 1), range.len);
|
||||||
try std.testing.expectEqualStrings("retry_backoff_multiplier", range[0].key);
|
try std.testing.expectEqualStrings("retry_backoff_multiplier", range[0].key);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test "deprecated settings warn instead of failing validation" {
|
||||||
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||||
|
defer arena.deinit();
|
||||||
|
const a = arena.allocator();
|
||||||
|
|
||||||
|
const ps = try problems(a, try testDoc(a,
|
||||||
|
\\ [service]
|
||||||
|
\\ max_concurrent_jobs = 4
|
||||||
|
\\ [load_levels]
|
||||||
|
\\ max_high_jobs = 2
|
||||||
|
));
|
||||||
|
try std.testing.expectEqual(@as(usize, 2), ps.len);
|
||||||
|
var saw_section = false;
|
||||||
|
var saw_key = false;
|
||||||
|
for (ps) |p| {
|
||||||
|
try std.testing.expect(p.is_warning);
|
||||||
|
try std.testing.expect(std.mem.indexOf(u8, p.message, "deprecated") != null);
|
||||||
|
if (std.mem.eql(u8, p.section, "load_levels")) saw_section = true;
|
||||||
|
if (std.mem.eql(u8, p.key, "max_concurrent_jobs")) saw_key = true;
|
||||||
|
}
|
||||||
|
try std.testing.expect(saw_section and saw_key);
|
||||||
|
|
||||||
|
// The deprecated values never make it into the config, and nothing errors.
|
||||||
|
const cfg = try fromDoc(a, try testDoc(a, "[service]\nmax_concurrent_jobs = 4\n[load_levels]\nmax_high_jobs = 2\n"), null);
|
||||||
|
try std.testing.expectEqual((Config{}).jobs.max_retries, cfg.jobs.max_retries);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "load reports deprecated settings from files and env" {
|
||||||
|
const io = std.testing.io;
|
||||||
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||||
|
defer arena.deinit();
|
||||||
|
const a = arena.allocator();
|
||||||
|
var tmp = std.testing.tmpDir(.{});
|
||||||
|
defer tmp.cleanup();
|
||||||
|
|
||||||
|
try tmp.dir.writeFile(io, .{ .sub_path = "old.conf", .data = "[service]\nmax_concurrent_jobs = 4\n[load_levels]\nmax_high_jobs = 2\n" });
|
||||||
|
|
||||||
|
var env = Environ.Map.init(std.testing.allocator);
|
||||||
|
defer env.deinit();
|
||||||
|
try env.put("ZAG_LOAD_LEVELS_MAX_HIGH_JOBS", "1");
|
||||||
|
|
||||||
|
var deprecations: std.ArrayList(Problem) = .empty;
|
||||||
|
const cfg = try load(a, io, &env, .{
|
||||||
|
.search_paths = &.{try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/old.conf", .{tmp.sub_path})},
|
||||||
|
}, null, &deprecations);
|
||||||
|
try std.testing.expectEqual(@as(usize, 3), deprecations.items.len);
|
||||||
|
for (deprecations.items) |p| {
|
||||||
|
try std.testing.expect(p.is_warning);
|
||||||
|
try std.testing.expect(std.mem.indexOf(u8, p.message, "deprecated") != null);
|
||||||
|
}
|
||||||
|
try std.testing.expectEqual(LogLevel.info, cfg.service.log_level);
|
||||||
|
}
|
||||||
|
|
||||||
|
test "deprecation warnings do not suppress the range check" {
|
||||||
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||||
|
defer arena.deinit();
|
||||||
|
const a = arena.allocator();
|
||||||
|
|
||||||
|
const ps = try problems(a, try testDoc(a,
|
||||||
|
\\[service]
|
||||||
|
\\max_concurrent_jobs = 4
|
||||||
|
\\[jobs]
|
||||||
|
\\retry_backoff_multiplier = 0.5
|
||||||
|
));
|
||||||
|
try std.testing.expectEqual(@as(usize, 2), ps.len);
|
||||||
|
var saw_warning = false;
|
||||||
|
var saw_range = false;
|
||||||
|
for (ps) |p| {
|
||||||
|
if (p.is_warning) saw_warning = true;
|
||||||
|
if (!p.is_warning and std.mem.eql(u8, p.key, "retry_backoff_multiplier")) saw_range = true;
|
||||||
|
}
|
||||||
|
try std.testing.expect(saw_warning and saw_range);
|
||||||
|
}
|
||||||
@@ -1,15 +1,9 @@
|
|||||||
//! Default configuration files embedded in the binary (written by `zag config install`).
|
//! Default configuration files embedded in the binary (written by `zag config install`).
|
||||||
pub const zag_conf = @embedFile("defaults/zag.conf");
|
pub const zag_conf = @embedFile("defaults/zag.conf");
|
||||||
pub const high_load = @embedFile("defaults/high.load");
|
|
||||||
pub const medium_load = @embedFile("defaults/medium.load");
|
|
||||||
pub const low_load = @embedFile("defaults/low.load");
|
|
||||||
|
|
||||||
pub const File = struct { name: []const u8, content: []const u8 };
|
pub const File = struct { name: []const u8, content: []const u8 };
|
||||||
|
|
||||||
/// Everything `config install` writes into the system config directory.
|
/// Everything `config install` writes into the system config directory.
|
||||||
pub const files = [_]File{
|
pub const files = [_]File{
|
||||||
.{ .name = "zag.conf", .content = zag_conf },
|
.{ .name = "zag.conf", .content = zag_conf },
|
||||||
.{ .name = "high.load", .content = high_load },
|
|
||||||
.{ .name = "medium.load", .content = medium_load },
|
|
||||||
.{ .name = "low.load", .content = low_load },
|
|
||||||
};
|
};
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
# High load commands - CPU/GPU intensive (transcoding, encoding)
|
|
||||||
# Maximum concurrent: 2 (default)
|
|
||||||
#
|
|
||||||
# Format:
|
|
||||||
# - Binary name: ffmpeg (matches any path ending with this executable)
|
|
||||||
# - Full path: /usr/local/bin/ffmpeg
|
|
||||||
# - Directory: /opt/encoders/ (trailing slash = match any executable in this directory)
|
|
||||||
|
|
||||||
ffmpeg
|
|
||||||
ffprobe
|
|
||||||
handbrake
|
|
||||||
HandBrakeCLI
|
|
||||||
x264
|
|
||||||
x265
|
|
||||||
av1an
|
|
||||||
svt-av1
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
# Low load commands - Network/IO intensive (downloads, uploads)
|
|
||||||
# Maximum concurrent: 32 (default)
|
|
||||||
#
|
|
||||||
# Format:
|
|
||||||
# - Binary name: curl (matches any path ending with this executable)
|
|
||||||
# - Full path: /usr/local/bin/rclone
|
|
||||||
# - Directory: /opt/downloaders/ (trailing slash = match any executable in this directory)
|
|
||||||
|
|
||||||
curl
|
|
||||||
wget
|
|
||||||
rclone
|
|
||||||
rsync
|
|
||||||
aria2c
|
|
||||||
scp
|
|
||||||
sftp
|
|
||||||
cadaver
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
# Medium load commands
|
|
||||||
# Maximum concurrent: 8 (default)
|
|
||||||
#
|
|
||||||
# Empty by default - unmatched commands are classified as MEDIUM
|
|
||||||
+2
-12
@@ -5,8 +5,8 @@
|
|||||||
# Logging verbosity: debug, info, warn, error
|
# Logging verbosity: debug, info, warn, error
|
||||||
log_level = "info"
|
log_level = "info"
|
||||||
|
|
||||||
# DEPRECATED: Use [load_levels] section instead
|
# Zag runs only one job at a time (strict FIFO by creation order);
|
||||||
# max_concurrent_jobs = 4
|
# concurrency is not configurable.
|
||||||
|
|
||||||
# How often running jobs update their heartbeat (seconds)
|
# How often running jobs update their heartbeat (seconds)
|
||||||
heartbeat_interval_seconds = 5
|
heartbeat_interval_seconds = 5
|
||||||
@@ -14,16 +14,6 @@ heartbeat_interval_seconds = 5
|
|||||||
# Heartbeat age before a job is considered orphaned (seconds)
|
# Heartbeat age before a job is considered orphaned (seconds)
|
||||||
stale_heartbeat_threshold_seconds = 30
|
stale_heartbeat_threshold_seconds = 30
|
||||||
|
|
||||||
[load_levels]
|
|
||||||
# Maximum concurrent high load jobs (CPU/GPU intensive)
|
|
||||||
max_high_jobs = 2
|
|
||||||
|
|
||||||
# Maximum concurrent medium load jobs (general purpose)
|
|
||||||
max_medium_jobs = 8
|
|
||||||
|
|
||||||
# Maximum concurrent low load jobs (network/IO intensive)
|
|
||||||
max_low_jobs = 32
|
|
||||||
|
|
||||||
[jobs]
|
[jobs]
|
||||||
# Maximum time a job can run before being killed (seconds)
|
# Maximum time a job can run before being killed (seconds)
|
||||||
default_timeout_seconds = 3600
|
default_timeout_seconds = 3600
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
//! Job and manifest data types. Timestamps are nanoseconds since the Unix epoch (`Instant`).
|
//! Job and manifest data types. Timestamps are nanoseconds since the Unix epoch (`Instant`).
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const State = @import("state.zig").State;
|
const State = @import("state.zig").State;
|
||||||
const LoadLevel = @import("loadlevel.zig").LoadLevel;
|
|
||||||
|
|
||||||
pub const Instant = i128;
|
pub const Instant = i128;
|
||||||
|
|
||||||
@@ -30,7 +29,6 @@ pub const Job = struct {
|
|||||||
heartbeat: ?Instant = null,
|
heartbeat: ?Instant = null,
|
||||||
retry_count: u32 = 0,
|
retry_count: u32 = 0,
|
||||||
retry_at: ?Instant = null,
|
retry_at: ?Instant = null,
|
||||||
load_level: LoadLevel = .medium,
|
|
||||||
|
|
||||||
pub fn isTerminal(self: Job) bool {
|
pub fn isTerminal(self: Job) bool {
|
||||||
return self.state.isTerminal();
|
return self.state.isTerminal();
|
||||||
@@ -54,7 +52,6 @@ pub const Manifest = struct {
|
|||||||
max_retries: u32 = 0,
|
max_retries: u32 = 0,
|
||||||
retry_delay_seconds: u32 = 30,
|
retry_delay_seconds: u32 = 30,
|
||||||
retry_backoff_multiplier: f64 = 2.0,
|
retry_backoff_multiplier: f64 = 2.0,
|
||||||
load_level: LoadLevel = .medium,
|
|
||||||
/// Per-job timeout in seconds; null uses the configured default.
|
/// Per-job timeout in seconds; null uses the configured default.
|
||||||
timeout_seconds: ?u32 = null,
|
timeout_seconds: ?u32 = null,
|
||||||
|
|
||||||
|
|||||||
+1
-9
@@ -1,12 +1,11 @@
|
|||||||
//! JSON representation of a `Job`, shared by `--output=json` and the IPC protocol.
|
//! JSON representation of a `Job`, shared by `--output=json` and the IPC protocol.
|
||||||
//! Field order matches barn: id, state (UPPERCASE), loadLevel, command, tag, timestamps,
|
//! Field order matches barn: id, state (UPPERCASE), command, tag, timestamps,
|
||||||
//! exitCode, error, pid, heartbeat, retryCount, retryAt, terminal, running, queued.
|
//! exitCode, error, pid, heartbeat, retryCount, retryAt, terminal, running, queued.
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const Allocator = std.mem.Allocator;
|
const Allocator = std.mem.Allocator;
|
||||||
const jsonpretty = @import("jsonpretty.zig");
|
const jsonpretty = @import("jsonpretty.zig");
|
||||||
const timestamp = @import("timestamp.zig");
|
const timestamp = @import("timestamp.zig");
|
||||||
const state_mod = @import("state.zig");
|
const state_mod = @import("state.zig");
|
||||||
const LoadLevel = @import("loadlevel.zig").LoadLevel;
|
|
||||||
const job_mod = @import("job.zig");
|
const job_mod = @import("job.zig");
|
||||||
const Job = job_mod.Job;
|
const Job = job_mod.Job;
|
||||||
const Instant = job_mod.Instant;
|
const Instant = job_mod.Instant;
|
||||||
@@ -33,7 +32,6 @@ pub fn writeJob(w: *jsonpretty.Writer, job: Job) !void {
|
|||||||
try w.beginObject();
|
try w.beginObject();
|
||||||
try w.field("id", .string, job.id);
|
try w.field("id", .string, job.id);
|
||||||
try w.field("state", .string, upperState(job.state));
|
try w.field("state", .string, upperState(job.state));
|
||||||
try w.field("loadLevel", .string, job.load_level.upper());
|
|
||||||
try w.key("command");
|
try w.key("command");
|
||||||
try w.beginArray();
|
try w.beginArray();
|
||||||
for (job.command) |arg| try w.string(arg);
|
for (job.command) |arg| try w.string(arg);
|
||||||
@@ -75,7 +73,6 @@ pub fn writeJobs(w: *jsonpretty.Writer, jobs: []const Job) !void {
|
|||||||
const RawJob = struct {
|
const RawJob = struct {
|
||||||
id: []const u8,
|
id: []const u8,
|
||||||
state: []const u8,
|
state: []const u8,
|
||||||
loadLevel: ?[]const u8 = null,
|
|
||||||
command: []const []const u8,
|
command: []const []const u8,
|
||||||
tag: ?[]const u8 = null,
|
tag: ?[]const u8 = null,
|
||||||
createdAt: []const u8,
|
createdAt: []const u8,
|
||||||
@@ -121,7 +118,6 @@ pub fn jobFromValue(arena: Allocator, value: std.json.Value) ParseError!Job {
|
|||||||
.heartbeat = try optInstant(raw.heartbeat),
|
.heartbeat = try optInstant(raw.heartbeat),
|
||||||
.retry_count = raw.retryCount,
|
.retry_count = raw.retryCount,
|
||||||
.retry_at = try optInstant(raw.retryAt),
|
.retry_at = try optInstant(raw.retryAt),
|
||||||
.load_level = if (raw.loadLevel) |l| LoadLevel.parse(l) orelse return error.InvalidJob else .medium,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,7 +142,6 @@ fn sampleJob() Job {
|
|||||||
.exit_code = .{ .code = 0 },
|
.exit_code = .{ .code = 0 },
|
||||||
.pid = 17486,
|
.pid = 17486,
|
||||||
.heartbeat = 1_769_046_527 * std.time.ns_per_s + 161_895_000,
|
.heartbeat = 1_769_046_527 * std.time.ns_per_s + 161_895_000,
|
||||||
.load_level = .medium,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,7 +154,6 @@ test "job JSON matches barn's field layout" {
|
|||||||
\\{
|
\\{
|
||||||
\\ "id" : "job-6d368040",
|
\\ "id" : "job-6d368040",
|
||||||
\\ "state" : "SUCCEEDED",
|
\\ "state" : "SUCCEEDED",
|
||||||
\\ "loadLevel" : "MEDIUM",
|
|
||||||
\\ "command" : [ "echo", "Hello World" ],
|
\\ "command" : [ "echo", "Hello World" ],
|
||||||
\\ "tag" : null,
|
\\ "tag" : null,
|
||||||
\\ "createdAt" : "2026-01-22T01:48:46.739979Z",
|
\\ "createdAt" : "2026-01-22T01:48:46.739979Z",
|
||||||
@@ -189,7 +183,6 @@ test "jobs round-trip through compact JSON" {
|
|||||||
failed.tag = "t";
|
failed.tag = "t";
|
||||||
failed.retry_count = 2;
|
failed.retry_count = 2;
|
||||||
failed.retry_at = failed.created_at + std.time.ns_per_s;
|
failed.retry_at = failed.created_at + std.time.ns_per_s;
|
||||||
failed.load_level = .low;
|
|
||||||
const jobs = [_]Job{ sampleJob(), failed };
|
const jobs = [_]Job{ sampleJob(), failed };
|
||||||
|
|
||||||
var aw: std.Io.Writer.Allocating = .init(a);
|
var aw: std.Io.Writer.Allocating = .init(a);
|
||||||
@@ -206,7 +199,6 @@ test "jobs round-trip through compact JSON" {
|
|||||||
try std.testing.expectEqualStrings("start_failed", back[1].exit_code.?.symbol);
|
try std.testing.expectEqualStrings("start_failed", back[1].exit_code.?.symbol);
|
||||||
try std.testing.expectEqualStrings("boom \"quoted\"", back[1].err.?);
|
try std.testing.expectEqualStrings("boom \"quoted\"", back[1].err.?);
|
||||||
try std.testing.expectEqual(@as(u32, 2), back[1].retry_count);
|
try std.testing.expectEqual(@as(u32, 2), back[1].retry_count);
|
||||||
try std.testing.expectEqual(LoadLevel.low, back[1].load_level);
|
|
||||||
try std.testing.expectEqual(failed.retry_at.?, back[1].retry_at.?);
|
try std.testing.expectEqual(failed.retry_at.?, back[1].retry_at.?);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,223 +0,0 @@
|
|||||||
//! Load-level classification from `high.load`, `medium.load` and `low.load` whitelist files.
|
|
||||||
//! Each line is a binary name (`ffmpeg`), a full path (`/usr/bin/ffmpeg`) or a directory
|
|
||||||
//! (`/opt/encoders/`); `#` starts a comment. HIGH is checked first, then MEDIUM, then LOW;
|
|
||||||
//! unmatched commands are MEDIUM. Port of barn's `LoadLevelClassifier` and `CommandMatcher`.
|
|
||||||
const std = @import("std");
|
|
||||||
const Io = std.Io;
|
|
||||||
const Allocator = std.mem.Allocator;
|
|
||||||
const LoadLevel = @import("loadlevel.zig").LoadLevel;
|
|
||||||
|
|
||||||
pub const Matcher = union(enum) {
|
|
||||||
/// Matches when the basename of the executable equals the name.
|
|
||||||
executable_name: []const u8,
|
|
||||||
/// Matches when the executable path equals this path.
|
|
||||||
full_path: []const u8,
|
|
||||||
/// Matches when the executable lives directly in this directory.
|
|
||||||
directory: []const u8,
|
|
||||||
|
|
||||||
pub fn matches(self: Matcher, command: []const []const u8) bool {
|
|
||||||
if (command.len == 0) return false;
|
|
||||||
const exe = command[0];
|
|
||||||
return switch (self) {
|
|
||||||
.executable_name => |n| std.mem.eql(u8, n, basename(exe)),
|
|
||||||
.full_path => |p| std.mem.eql(u8, normalize(p), normalize(exe)),
|
|
||||||
.directory => |d| if (dirname(exe)) |parent|
|
|
||||||
std.mem.eql(u8, normalize(parent), normalize(d))
|
|
||||||
else
|
|
||||||
false,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fn basename(path: []const u8) []const u8 {
|
|
||||||
const t = std.mem.trimEnd(u8, path, "/");
|
|
||||||
const i = std.mem.lastIndexOfScalar(u8, t, '/') orelse return t;
|
|
||||||
return t[i + 1 ..];
|
|
||||||
}
|
|
||||||
|
|
||||||
fn dirname(path: []const u8) ?[]const u8 {
|
|
||||||
const t = std.mem.trimEnd(u8, path, "/");
|
|
||||||
const i = std.mem.lastIndexOfScalar(u8, t, '/') orelse return null;
|
|
||||||
if (i == 0) return "/";
|
|
||||||
return t[0..i];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Strips trailing slashes (keeping a lone `/`).
|
|
||||||
fn normalize(path: []const u8) []const u8 {
|
|
||||||
if (path.len <= 1) return path;
|
|
||||||
const t = std.mem.trimEnd(u8, path, "/");
|
|
||||||
return if (t.len == 0) "/" else t;
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn parseEntry(entry: []const u8) Matcher {
|
|
||||||
if (std.mem.endsWith(u8, entry, "/")) return .{ .directory = entry };
|
|
||||||
if (std.mem.indexOfScalar(u8, entry, '/') != null) return .{ .full_path = entry };
|
|
||||||
return .{ .executable_name = entry };
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Parses a `.load` file body. Slices point into `text`; the list is allocated from `arena`.
|
|
||||||
pub fn parseLoadFile(arena: Allocator, text: []const u8) Allocator.Error![]const Matcher {
|
|
||||||
var list: std.ArrayList(Matcher) = .empty;
|
|
||||||
var lines = std.mem.splitScalar(u8, text, '\n');
|
|
||||||
while (lines.next()) |raw| {
|
|
||||||
const line = std.mem.trim(u8, raw, &std.ascii.whitespace);
|
|
||||||
if (line.len == 0 or line[0] == '#') continue;
|
|
||||||
try list.append(arena, parseEntry(line));
|
|
||||||
}
|
|
||||||
return list.toOwnedSlice(arena);
|
|
||||||
}
|
|
||||||
|
|
||||||
pub const Classifier = struct {
|
|
||||||
high: []const Matcher = &.{},
|
|
||||||
medium: []const Matcher = &.{},
|
|
||||||
low: []const Matcher = &.{},
|
|
||||||
|
|
||||||
pub fn classify(self: Classifier, command: []const []const u8) LoadLevel {
|
|
||||||
if (command.len == 0) return .default;
|
|
||||||
for (self.high) |m| if (m.matches(command)) return .high;
|
|
||||||
for (self.medium) |m| if (m.matches(command)) return .medium;
|
|
||||||
for (self.low) |m| if (m.matches(command)) return .low;
|
|
||||||
return .default;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads the three files from `config_dir`; missing or unreadable files count as empty.
|
|
||||||
pub fn load(arena: Allocator, io: Io, config_dir: []const u8) Allocator.Error!Classifier {
|
|
||||||
return .{
|
|
||||||
.high = try loadOne(arena, io, config_dir, "high.load"),
|
|
||||||
.medium = try loadOne(arena, io, config_dir, "medium.load"),
|
|
||||||
.low = try loadOne(arena, io, config_dir, "low.load"),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// True when at least one of the three `.load` files exists in `config_dir`.
|
|
||||||
pub fn anyFileExists(io: Io, config_dir: []const u8) bool {
|
|
||||||
var buf: [512]u8 = undefined;
|
|
||||||
for ([_][]const u8{ "high.load", "medium.load", "low.load" }) |name| {
|
|
||||||
const path = std.fmt.bufPrint(&buf, "{s}/{s}", .{ config_dir, name }) catch continue;
|
|
||||||
if (Io.Dir.cwd().statFile(io, path, .{})) |_| return true else |_| {}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Loads from `config_dir` when it holds any `.load` file, else uses the embedded defaults
|
|
||||||
/// (so `ffmpeg` is HIGH and `curl` is LOW even before `zag config install`).
|
|
||||||
pub fn loadOrDefaults(arena: Allocator, io: Io, config_dir: []const u8) Allocator.Error!Classifier {
|
|
||||||
if (anyFileExists(io, config_dir)) return load(arena, io, config_dir);
|
|
||||||
return fromDefaults(arena);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Classifier built from the embedded default files.
|
|
||||||
pub fn fromDefaults(arena: Allocator) Allocator.Error!Classifier {
|
|
||||||
const defaults = @import("defaults.zig");
|
|
||||||
return .{
|
|
||||||
.high = try parseLoadFile(arena, defaults.high_load),
|
|
||||||
.medium = try parseLoadFile(arena, defaults.medium_load),
|
|
||||||
.low = try parseLoadFile(arena, defaults.low_load),
|
|
||||||
};
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
fn loadOne(arena: Allocator, io: Io, dir: []const u8, name: []const u8) Allocator.Error![]const Matcher {
|
|
||||||
const path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ dir, name });
|
|
||||||
const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| switch (err) {
|
|
||||||
error.OutOfMemory => return error.OutOfMemory,
|
|
||||||
else => return &.{},
|
|
||||||
};
|
|
||||||
return parseLoadFile(arena, text);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn cmd(comptime args: []const []const u8) []const []const u8 {
|
|
||||||
return args;
|
|
||||||
}
|
|
||||||
|
|
||||||
test "entry kinds" {
|
|
||||||
try std.testing.expectEqualStrings("ffmpeg", parseEntry("ffmpeg").executable_name);
|
|
||||||
try std.testing.expectEqualStrings("/usr/bin/ffmpeg", parseEntry("/usr/bin/ffmpeg").full_path);
|
|
||||||
try std.testing.expectEqualStrings("/opt/encoders/", parseEntry("/opt/encoders/").directory);
|
|
||||||
}
|
|
||||||
|
|
||||||
test "executable name matches any path ending with it" {
|
|
||||||
const m = parseEntry("ffmpeg");
|
|
||||||
try std.testing.expect(m.matches(cmd(&.{ "ffmpeg", "-i", "x" })));
|
|
||||||
try std.testing.expect(m.matches(cmd(&.{"/usr/local/bin/ffmpeg"})));
|
|
||||||
try std.testing.expect(!m.matches(cmd(&.{"ffmpeg2"})));
|
|
||||||
try std.testing.expect(!m.matches(cmd(&.{ "echo", "ffmpeg" })));
|
|
||||||
try std.testing.expect(!m.matches(&.{}));
|
|
||||||
}
|
|
||||||
|
|
||||||
test "full path and directory matching" {
|
|
||||||
const fp = parseEntry("/usr/local/bin/rclone");
|
|
||||||
try std.testing.expect(fp.matches(cmd(&.{ "/usr/local/bin/rclone", "copy" })));
|
|
||||||
try std.testing.expect(!fp.matches(cmd(&.{"rclone"})));
|
|
||||||
try std.testing.expect(!fp.matches(cmd(&.{"/usr/bin/rclone"})));
|
|
||||||
|
|
||||||
const d = parseEntry("/opt/encoders/");
|
|
||||||
try std.testing.expect(d.matches(cmd(&.{"/opt/encoders/x265"})));
|
|
||||||
try std.testing.expect(d.matches(cmd(&.{"/opt/encoders//x265"})));
|
|
||||||
try std.testing.expect(!d.matches(cmd(&.{"/opt/encoders/sub/x265"})));
|
|
||||||
try std.testing.expect(!d.matches(cmd(&.{"x265"})));
|
|
||||||
}
|
|
||||||
|
|
||||||
test "load files skip comments and blanks" {
|
|
||||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
||||||
defer arena.deinit();
|
|
||||||
const ms = try parseLoadFile(arena.allocator(), "# c\n\n ffmpeg \n/opt/x/\n # more\ncurl\n");
|
|
||||||
try std.testing.expectEqual(@as(usize, 3), ms.len);
|
|
||||||
}
|
|
||||||
|
|
||||||
test "priority is high, then medium, then low, default medium" {
|
|
||||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
||||||
defer arena.deinit();
|
|
||||||
const a = arena.allocator();
|
|
||||||
const c: Classifier = .{
|
|
||||||
.high = try parseLoadFile(a, "ffmpeg\n"),
|
|
||||||
.medium = try parseLoadFile(a, "both\n"),
|
|
||||||
.low = try parseLoadFile(a, "curl\nboth\nffmpeg\n"),
|
|
||||||
};
|
|
||||||
try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{"ffmpeg"})));
|
|
||||||
try std.testing.expectEqual(LoadLevel.low, c.classify(cmd(&.{"curl"})));
|
|
||||||
try std.testing.expectEqual(LoadLevel.medium, c.classify(cmd(&.{"both"})));
|
|
||||||
try std.testing.expectEqual(LoadLevel.medium, c.classify(cmd(&.{"echo"})));
|
|
||||||
try std.testing.expectEqual(LoadLevel.medium, c.classify(&.{}));
|
|
||||||
}
|
|
||||||
|
|
||||||
test "embedded defaults classify ffmpeg high and curl low" {
|
|
||||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
||||||
defer arena.deinit();
|
|
||||||
const c = try Classifier.fromDefaults(arena.allocator());
|
|
||||||
try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{ "ffprobe", "-i", "x" })));
|
|
||||||
try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{"/usr/bin/HandBrakeCLI"})));
|
|
||||||
try std.testing.expectEqual(LoadLevel.low, c.classify(cmd(&.{ "curl", "-O", "u" })));
|
|
||||||
try std.testing.expectEqual(LoadLevel.medium, c.classify(cmd(&.{ "echo", "hi" })));
|
|
||||||
}
|
|
||||||
|
|
||||||
test "load reads files from a directory and tolerates missing ones" {
|
|
||||||
const io = std.testing.io;
|
|
||||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
||||||
defer arena.deinit();
|
|
||||||
const a = arena.allocator();
|
|
||||||
var tmp = std.testing.tmpDir(.{});
|
|
||||||
defer tmp.cleanup();
|
|
||||||
try tmp.dir.writeFile(io, .{ .sub_path = "high.load", .data = "mytool\n" });
|
|
||||||
const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path});
|
|
||||||
const c = try Classifier.load(a, io, dir);
|
|
||||||
try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{"mytool"})));
|
|
||||||
try std.testing.expectEqual(@as(usize, 0), c.low.len);
|
|
||||||
}
|
|
||||||
|
|
||||||
test "loadOrDefaults falls back to the embedded lists when no file exists" {
|
|
||||||
const io = std.testing.io;
|
|
||||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
||||||
defer arena.deinit();
|
|
||||||
const a = arena.allocator();
|
|
||||||
var tmp = std.testing.tmpDir(.{});
|
|
||||||
defer tmp.cleanup();
|
|
||||||
const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path});
|
|
||||||
|
|
||||||
const defaults = try Classifier.loadOrDefaults(a, io, dir);
|
|
||||||
try std.testing.expectEqual(LoadLevel.high, defaults.classify(cmd(&.{"ffmpeg"})));
|
|
||||||
|
|
||||||
try tmp.dir.writeFile(io, .{ .sub_path = "low.load", .data = "ffmpeg\n" });
|
|
||||||
const custom = try Classifier.loadOrDefaults(a, io, dir);
|
|
||||||
try std.testing.expectEqual(LoadLevel.low, custom.classify(cmd(&.{"ffmpeg"})));
|
|
||||||
}
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
//! Load levels cap how many jobs of each weight run at once.
|
|
||||||
const std = @import("std");
|
|
||||||
|
|
||||||
pub const LoadLevel = enum {
|
|
||||||
high,
|
|
||||||
medium,
|
|
||||||
low,
|
|
||||||
|
|
||||||
pub const default: LoadLevel = .medium;
|
|
||||||
|
|
||||||
pub fn defaultMaxJobs(self: LoadLevel) u32 {
|
|
||||||
return switch (self) {
|
|
||||||
.high => 2,
|
|
||||||
.medium => 8,
|
|
||||||
.low => 32,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn lower(self: LoadLevel) []const u8 {
|
|
||||||
return @tagName(self);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Uppercase form used in JSON (`HIGH`, `MEDIUM`, `LOW`) and manifests.
|
|
||||||
pub fn upper(self: LoadLevel) []const u8 {
|
|
||||||
return switch (self) {
|
|
||||||
.high => "HIGH",
|
|
||||||
.medium => "MEDIUM",
|
|
||||||
.low => "LOW",
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Case-insensitive; surrounding whitespace is ignored.
|
|
||||||
pub fn parse(text: []const u8) ?LoadLevel {
|
|
||||||
const t = std.mem.trim(u8, text, &std.ascii.whitespace);
|
|
||||||
inline for (@typeInfo(LoadLevel).@"enum".fields) |f| {
|
|
||||||
if (std.ascii.eqlIgnoreCase(t, f.name)) return @field(LoadLevel, f.name);
|
|
||||||
}
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
test "defaults and names" {
|
|
||||||
try std.testing.expectEqual(LoadLevel.medium, LoadLevel.default);
|
|
||||||
try std.testing.expectEqual(@as(u32, 2), LoadLevel.high.defaultMaxJobs());
|
|
||||||
try std.testing.expectEqual(@as(u32, 8), LoadLevel.medium.defaultMaxJobs());
|
|
||||||
try std.testing.expectEqual(@as(u32, 32), LoadLevel.low.defaultMaxJobs());
|
|
||||||
try std.testing.expectEqualStrings("HIGH", LoadLevel.high.upper());
|
|
||||||
try std.testing.expectEqualStrings("low", LoadLevel.low.lower());
|
|
||||||
}
|
|
||||||
|
|
||||||
test "parse is case-insensitive and trims" {
|
|
||||||
try std.testing.expectEqual(LoadLevel.high, LoadLevel.parse(" High ").?);
|
|
||||||
try std.testing.expectEqual(LoadLevel.low, LoadLevel.parse("LOW").?);
|
|
||||||
try std.testing.expect(LoadLevel.parse("extreme") == null);
|
|
||||||
try std.testing.expect(LoadLevel.parse("") == null);
|
|
||||||
}
|
|
||||||
@@ -196,7 +196,6 @@ fn xmlJob(out: *Io.Writer, job: Job, depth: usize) !void {
|
|||||||
if (job.heartbeat) |t| try xmlJobTime(out, d, "heartbeat", t);
|
if (job.heartbeat) |t| try xmlJobTime(out, d, "heartbeat", t);
|
||||||
if (job.retry_count > 0) try xmlLeaf(out, d, "retry_count", "{d}", .{job.retry_count});
|
if (job.retry_count > 0) try xmlLeaf(out, d, "retry_count", "{d}", .{job.retry_count});
|
||||||
if (job.retry_at) |t| try xmlJobTime(out, d, "retry_at", t);
|
if (job.retry_at) |t| try xmlJobTime(out, d, "retry_at", t);
|
||||||
try xmlLeaf(out, d, "load_level", "{s}", .{job.load_level.lower()});
|
|
||||||
try indent(out, depth);
|
try indent(out, depth);
|
||||||
try out.writeAll("</job>\n");
|
try out.writeAll("</job>\n");
|
||||||
}
|
}
|
||||||
@@ -522,7 +521,6 @@ test "XML job follows barn's element shape" {
|
|||||||
\\ <created_at>2026-01-22T01:48:46Z</created_at>
|
\\ <created_at>2026-01-22T01:48:46Z</created_at>
|
||||||
\\ <exit_code>0</exit_code>
|
\\ <exit_code>0</exit_code>
|
||||||
\\ <pid>17486</pid>
|
\\ <pid>17486</pid>
|
||||||
\\ <load_level>medium</load_level>
|
|
||||||
\\</job>
|
\\</job>
|
||||||
\\
|
\\
|
||||||
);
|
);
|
||||||
|
|||||||
+1
-1
@@ -185,7 +185,7 @@ test "signalTree kills the whole process group" {
|
|||||||
}
|
}
|
||||||
|
|
||||||
test "isAlive" {
|
test "isAlive" {
|
||||||
try std.testing.expect(isAlive(std.os.linux.getpid()));
|
try std.testing.expect(isAlive(currentPid()));
|
||||||
try std.testing.expect(!isAlive(-1));
|
try std.testing.expect(!isAlive(-1));
|
||||||
try std.testing.expect(!isAlive(0));
|
try std.testing.expect(!isAlive(0));
|
||||||
}
|
}
|
||||||
+1
-1
@@ -73,7 +73,7 @@ test "stale and orphaned detection" {
|
|||||||
j.heartbeat = now - 60 * std.time.ns_per_s;
|
j.heartbeat = now - 60 * std.time.ns_per_s;
|
||||||
try std.testing.expect(isStale(j, now, 30));
|
try std.testing.expect(isStale(j, now, 30));
|
||||||
try std.testing.expect(isOrphaned(j, now, 30)); // pid does not exist
|
try std.testing.expect(isOrphaned(j, now, 30)); // pid does not exist
|
||||||
j.pid = std.os.linux.getpid();
|
j.pid = proc.currentPid();
|
||||||
try std.testing.expect(!isOrphaned(j, now, 30)); // alive: stale but not orphaned
|
try std.testing.expect(!isOrphaned(j, now, 30)); // alive: stale but not orphaned
|
||||||
j.pid = null;
|
j.pid = null;
|
||||||
try std.testing.expect(isOrphaned(j, now, 30));
|
try std.testing.expect(isOrphaned(j, now, 30));
|
||||||
|
|||||||
+12
-17
@@ -9,7 +9,6 @@ const Dirs = @import("dirs.zig").Dirs;
|
|||||||
const dirs_mod = @import("dirs.zig");
|
const dirs_mod = @import("dirs.zig");
|
||||||
const StateFiles = @import("statefiles.zig").StateFiles;
|
const StateFiles = @import("statefiles.zig").StateFiles;
|
||||||
const State = @import("state.zig").State;
|
const State = @import("state.zig").State;
|
||||||
const LoadLevel = @import("loadlevel.zig").LoadLevel;
|
|
||||||
const job_mod = @import("job.zig");
|
const job_mod = @import("job.zig");
|
||||||
const Job = job_mod.Job;
|
const Job = job_mod.Job;
|
||||||
const Manifest = job_mod.Manifest;
|
const Manifest = job_mod.Manifest;
|
||||||
@@ -26,7 +25,6 @@ pub const Error = error{ InvalidTransition, JobNotFound, InvalidManifest };
|
|||||||
|
|
||||||
pub const CreateOptions = struct {
|
pub const CreateOptions = struct {
|
||||||
tag: ?[]const u8 = null,
|
tag: ?[]const u8 = null,
|
||||||
load_level: LoadLevel = .medium,
|
|
||||||
max_retries: u32 = 3,
|
max_retries: u32 = 3,
|
||||||
retry_delay_seconds: u32 = 30,
|
retry_delay_seconds: u32 = 30,
|
||||||
retry_backoff_multiplier: f64 = 2.0,
|
retry_backoff_multiplier: f64 = 2.0,
|
||||||
@@ -66,7 +64,6 @@ pub const Repository = struct {
|
|||||||
.max_retries = opts.max_retries,
|
.max_retries = opts.max_retries,
|
||||||
.retry_delay_seconds = opts.retry_delay_seconds,
|
.retry_delay_seconds = opts.retry_delay_seconds,
|
||||||
.retry_backoff_multiplier = opts.retry_backoff_multiplier,
|
.retry_backoff_multiplier = opts.retry_backoff_multiplier,
|
||||||
.load_level = opts.load_level,
|
|
||||||
.timeout_seconds = opts.timeout_seconds,
|
.timeout_seconds = opts.timeout_seconds,
|
||||||
};
|
};
|
||||||
try manifest.validate();
|
try manifest.validate();
|
||||||
@@ -93,7 +90,6 @@ pub const Repository = struct {
|
|||||||
.command = command,
|
.command = command,
|
||||||
.tag = opts.tag,
|
.tag = opts.tag,
|
||||||
.created_at = manifest.created_at,
|
.created_at = manifest.created_at,
|
||||||
.load_level = opts.load_level,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -159,7 +155,6 @@ pub const Repository = struct {
|
|||||||
.heartbeat = try sf.readHeartbeat(),
|
.heartbeat = try sf.readHeartbeat(),
|
||||||
.retry_count = (try sf.readRetryCount()) orelse 0,
|
.retry_count = (try sf.readRetryCount()) orelse 0,
|
||||||
.retry_at = try sf.readRetryAt(),
|
.retry_at = try sf.readRetryAt(),
|
||||||
.load_level = manifest.load_level,
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -299,7 +294,6 @@ pub fn writeManifestJson(out: *Io.Writer, m: Manifest) !void {
|
|||||||
try w.field("maxRetries", .int, m.max_retries);
|
try w.field("maxRetries", .int, m.max_retries);
|
||||||
try w.field("retryDelaySeconds", .int, m.retry_delay_seconds);
|
try w.field("retryDelaySeconds", .int, m.retry_delay_seconds);
|
||||||
try w.field("retryBackoffMultiplier", .float, m.retry_backoff_multiplier);
|
try w.field("retryBackoffMultiplier", .float, m.retry_backoff_multiplier);
|
||||||
try w.field("loadLevel", .string, m.load_level.upper());
|
|
||||||
if (m.timeout_seconds) |t| try w.field("timeoutSeconds", .int, t);
|
if (m.timeout_seconds) |t| try w.field("timeoutSeconds", .int, t);
|
||||||
try w.endObject();
|
try w.endObject();
|
||||||
}
|
}
|
||||||
@@ -312,11 +306,11 @@ const RawManifest = struct {
|
|||||||
maxRetries: u32 = 0,
|
maxRetries: u32 = 0,
|
||||||
retryDelaySeconds: u32 = 30,
|
retryDelaySeconds: u32 = 30,
|
||||||
retryBackoffMultiplier: f64 = 2.0,
|
retryBackoffMultiplier: f64 = 2.0,
|
||||||
loadLevel: ?[]const u8 = null,
|
|
||||||
timeoutSeconds: ?u32 = null,
|
timeoutSeconds: ?u32 = null,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Parses a barn- or zag-written `manifest.json`. A missing `loadLevel` defaults to MEDIUM.
|
/// Parses a barn- or zag-written `manifest.json`; unknown fields (e.g. barn's `loadLevel`)
|
||||||
|
/// are ignored.
|
||||||
pub fn parseManifestJson(arena: Allocator, text: []const u8) !Manifest {
|
pub fn parseManifestJson(arena: Allocator, text: []const u8) !Manifest {
|
||||||
const raw = std.json.parseFromSliceLeaky(RawManifest, arena, text, .{ .ignore_unknown_fields = true }) catch
|
const raw = std.json.parseFromSliceLeaky(RawManifest, arena, text, .{ .ignore_unknown_fields = true }) catch
|
||||||
return error.InvalidManifest;
|
return error.InvalidManifest;
|
||||||
@@ -328,7 +322,6 @@ pub fn parseManifestJson(arena: Allocator, text: []const u8) !Manifest {
|
|||||||
.max_retries = raw.maxRetries,
|
.max_retries = raw.maxRetries,
|
||||||
.retry_delay_seconds = raw.retryDelaySeconds,
|
.retry_delay_seconds = raw.retryDelaySeconds,
|
||||||
.retry_backoff_multiplier = raw.retryBackoffMultiplier,
|
.retry_backoff_multiplier = raw.retryBackoffMultiplier,
|
||||||
.load_level = if (raw.loadLevel) |l| LoadLevel.parse(l) orelse return error.InvalidManifest else .medium,
|
|
||||||
.timeout_seconds = raw.timeoutSeconds,
|
.timeout_seconds = raw.timeoutSeconds,
|
||||||
};
|
};
|
||||||
m.validate() catch return error.InvalidManifest;
|
m.validate() catch return error.InvalidManifest;
|
||||||
@@ -373,7 +366,6 @@ test "manifest JSON matches barn's layout and round-trips" {
|
|||||||
.max_retries = 3,
|
.max_retries = 3,
|
||||||
.retry_delay_seconds = 30,
|
.retry_delay_seconds = 30,
|
||||||
.retry_backoff_multiplier = 2.0,
|
.retry_backoff_multiplier = 2.0,
|
||||||
.load_level = .high,
|
|
||||||
};
|
};
|
||||||
var aw: Io.Writer.Allocating = .init(arena.allocator());
|
var aw: Io.Writer.Allocating = .init(arena.allocator());
|
||||||
try writeManifestJson(&aw.writer, m);
|
try writeManifestJson(&aw.writer, m);
|
||||||
@@ -385,25 +377,22 @@ test "manifest JSON matches barn's layout and round-trips" {
|
|||||||
\\ "createdAt" : "2026-01-22T01:48:46Z",
|
\\ "createdAt" : "2026-01-22T01:48:46Z",
|
||||||
\\ "maxRetries" : 3,
|
\\ "maxRetries" : 3,
|
||||||
\\ "retryDelaySeconds" : 30,
|
\\ "retryDelaySeconds" : 30,
|
||||||
\\ "retryBackoffMultiplier" : 2.0,
|
\\ "retryBackoffMultiplier" : 2.0
|
||||||
\\ "loadLevel" : "HIGH"
|
|
||||||
\\}
|
\\}
|
||||||
, aw.written());
|
, aw.written());
|
||||||
const back = try parseManifestJson(arena.allocator(), aw.written());
|
const back = try parseManifestJson(arena.allocator(), aw.written());
|
||||||
try std.testing.expectEqualStrings("job-6d368040", back.id);
|
try std.testing.expectEqualStrings("job-6d368040", back.id);
|
||||||
try std.testing.expectEqual(m.created_at, back.created_at);
|
try std.testing.expectEqual(m.created_at, back.created_at);
|
||||||
try std.testing.expectEqual(LoadLevel.high, back.load_level);
|
|
||||||
try std.testing.expectEqualStrings("Hello World", back.command[1]);
|
try std.testing.expectEqualStrings("Hello World", back.command[1]);
|
||||||
}
|
}
|
||||||
|
|
||||||
test "manifest without loadLevel (older barn jobs) defaults to medium" {
|
test "manifest without optional fields (older barn jobs) still parses" {
|
||||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||||
defer arena.deinit();
|
defer arena.deinit();
|
||||||
const m = try parseManifestJson(arena.allocator(),
|
const m = try parseManifestJson(arena.allocator(),
|
||||||
\\{"id":"job-1","command":["ls"],"tag":"t","createdAt":"2026-01-22T01:48:46.749629Z",
|
\\{"id":"job-1","command":["ls"],"tag":"t","createdAt":"2026-01-22T01:48:46.749629Z",
|
||||||
\\ "maxRetries":0,"retryDelaySeconds":30,"retryBackoffMultiplier":2.0}
|
\\ "maxRetries":0,"retryDelaySeconds":30,"retryBackoffMultiplier":2.0}
|
||||||
);
|
);
|
||||||
try std.testing.expectEqual(LoadLevel.medium, m.load_level);
|
|
||||||
try std.testing.expectEqualStrings("t", m.tag.?);
|
try std.testing.expectEqualStrings("t", m.tag.?);
|
||||||
try std.testing.expectError(error.InvalidManifest, parseManifestJson(arena.allocator(), "{}"));
|
try std.testing.expectError(error.InvalidManifest, parseManifestJson(arena.allocator(), "{}"));
|
||||||
try std.testing.expectError(error.InvalidManifest, parseManifestJson(arena.allocator(),
|
try std.testing.expectError(error.InvalidManifest, parseManifestJson(arena.allocator(),
|
||||||
@@ -411,18 +400,24 @@ test "manifest without loadLevel (older barn jobs) defaults to medium" {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test "manifest with unknown loadLevel field (upgraded from older zag) still parses" {
|
||||||
|
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||||
|
defer arena.deinit();
|
||||||
|
const m = try parseManifestJson(arena.allocator(), "{\"id\":\"job-2\",\"command\":[\"ls\"],\"createdAt\":\"2026-01-22T01:48:46.749629Z\",\"loadLevel\":\"HIGH\"}");
|
||||||
|
try std.testing.expectEqualStrings("job-2", m.id);
|
||||||
|
}
|
||||||
|
|
||||||
test "create then find" {
|
test "create then find" {
|
||||||
const env = try TestEnv.init();
|
const env = try TestEnv.init();
|
||||||
defer env.deinit();
|
defer env.deinit();
|
||||||
const a = env.arena.allocator();
|
const a = env.arena.allocator();
|
||||||
|
|
||||||
const created = try env.repo().create(a, &.{ "echo", "hi" }, .{ .tag = "downloading", .load_level = .low });
|
const created = try env.repo().create(a, &.{ "echo", "hi" }, .{ .tag = "downloading" });
|
||||||
try std.testing.expect(jobid.isValid(created.id));
|
try std.testing.expect(jobid.isValid(created.id));
|
||||||
try std.testing.expectEqual(State.queued, created.state);
|
try std.testing.expectEqual(State.queued, created.state);
|
||||||
|
|
||||||
const found = (try env.repo().findById(a, created.id)).?;
|
const found = (try env.repo().findById(a, created.id)).?;
|
||||||
try std.testing.expectEqualStrings("downloading", found.tag.?);
|
try std.testing.expectEqualStrings("downloading", found.tag.?);
|
||||||
try std.testing.expectEqual(LoadLevel.low, found.load_level);
|
|
||||||
try std.testing.expectEqual(@as(u32, 0), found.retry_count);
|
try std.testing.expectEqual(@as(u32, 0), found.retry_count);
|
||||||
try std.testing.expectEqual(created.created_at, found.created_at);
|
try std.testing.expectEqual(created.created_at, found.created_at);
|
||||||
try std.testing.expectEqualStrings("hi", found.command[1]);
|
try std.testing.expectEqualStrings("hi", found.command[1]);
|
||||||
|
|||||||
@@ -13,14 +13,12 @@ pub const jobid = @import("jobid.zig");
|
|||||||
pub const fsutil = @import("fsutil.zig");
|
pub const fsutil = @import("fsutil.zig");
|
||||||
pub const jsonpretty = @import("jsonpretty.zig");
|
pub const jsonpretty = @import("jsonpretty.zig");
|
||||||
pub const toml = @import("toml.zig");
|
pub const toml = @import("toml.zig");
|
||||||
pub const loadlevel = @import("loadlevel.zig");
|
|
||||||
pub const job = @import("job.zig");
|
pub const job = @import("job.zig");
|
||||||
pub const dirs = @import("dirs.zig");
|
pub const dirs = @import("dirs.zig");
|
||||||
pub const statefiles = @import("statefiles.zig");
|
pub const statefiles = @import("statefiles.zig");
|
||||||
pub const repository = @import("repository.zig");
|
pub const repository = @import("repository.zig");
|
||||||
pub const defaults = @import("defaults.zig");
|
pub const defaults = @import("defaults.zig");
|
||||||
pub const config = @import("config.zig");
|
pub const config = @import("config.zig");
|
||||||
pub const loadclass = @import("loadclass.zig");
|
|
||||||
pub const retry = @import("retry.zig");
|
pub const retry = @import("retry.zig");
|
||||||
pub const proc = @import("proc.zig");
|
pub const proc = @import("proc.zig");
|
||||||
pub const runner = @import("runner.zig");
|
pub const runner = @import("runner.zig");
|
||||||
|
|||||||
+31
-86
@@ -1,7 +1,8 @@
|
|||||||
//! Job scheduler: polls for queued jobs, enforces per-load-level concurrency limits and runs
|
//! Job scheduler: polls for queued jobs and runs them one at a time, each on its own thread.
|
||||||
//! each job on its own thread. Port of barn's `JobScheduler`.
|
//! Port of barn's `JobScheduler` (with the per-load-level concurrency limits removed).
|
||||||
//!
|
//!
|
||||||
//! Jobs start oldest-first (by `created_at`), skipping ones whose `retry_at` is in the future.
|
//! Only one job runs at a time; queued jobs start oldest-first (by `created_at`), skipping
|
||||||
|
//! ones whose `retry_at` is in the future.
|
||||||
//! Only one scheduler may run per base directory (guarded by `locks/scheduler.lock`).
|
//! Only one scheduler may run per base directory (guarded by `locks/scheduler.lock`).
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const Io = std.Io;
|
const Io = std.Io;
|
||||||
@@ -11,12 +12,9 @@ const dirs_mod = @import("dirs.zig");
|
|||||||
const fsutil = @import("fsutil.zig");
|
const fsutil = @import("fsutil.zig");
|
||||||
const runner = @import("runner.zig");
|
const runner = @import("runner.zig");
|
||||||
const timestamp = @import("timestamp.zig");
|
const timestamp = @import("timestamp.zig");
|
||||||
const LoadLevel = @import("loadlevel.zig").LoadLevel;
|
|
||||||
const LoadLevels = @import("config.zig").LoadLevels;
|
|
||||||
const Job = @import("job.zig").Job;
|
const Job = @import("job.zig").Job;
|
||||||
|
|
||||||
pub const Options = struct {
|
pub const Options = struct {
|
||||||
limits: LoadLevels = .{},
|
|
||||||
/// Poll interval.
|
/// Poll interval.
|
||||||
tick_ms: u64 = 1_000,
|
tick_ms: u64 = 1_000,
|
||||||
runner: runner.Options = .{},
|
runner: runner.Options = .{},
|
||||||
@@ -35,7 +33,6 @@ pub const KillResult = enum {
|
|||||||
const Active = struct {
|
const Active = struct {
|
||||||
id: []u8,
|
id: []u8,
|
||||||
ctl: runner.Control = .{},
|
ctl: runner.Control = .{},
|
||||||
level: LoadLevel,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const Scheduler = struct {
|
pub const Scheduler = struct {
|
||||||
@@ -46,7 +43,6 @@ pub const Scheduler = struct {
|
|||||||
|
|
||||||
mutex: Io.Mutex = .init,
|
mutex: Io.Mutex = .init,
|
||||||
active: std.StringHashMapUnmanaged(*Active) = .empty,
|
active: std.StringHashMapUnmanaged(*Active) = .empty,
|
||||||
counts: [3]u32 = .{ 0, 0, 0 },
|
|
||||||
stopping: std.atomic.Value(bool) = .init(false),
|
stopping: std.atomic.Value(bool) = .init(false),
|
||||||
thread: ?std.Thread = null,
|
thread: ?std.Thread = null,
|
||||||
lock: ?fsutil.FileLock = null,
|
lock: ?fsutil.FileLock = null,
|
||||||
@@ -101,19 +97,6 @@ pub const Scheduler = struct {
|
|||||||
return self.active.count();
|
return self.active.count();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn runningAt(self: *Scheduler, level: LoadLevel) u32 {
|
|
||||||
self.mutex.lockUncancelable(self.io);
|
|
||||||
defer self.mutex.unlock(self.io);
|
|
||||||
return self.counts[@intFromEnum(level)];
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Applies new concurrency limits; running jobs are unaffected.
|
|
||||||
pub fn setLimits(self: *Scheduler, limits: LoadLevels) void {
|
|
||||||
self.mutex.lockUncancelable(self.io);
|
|
||||||
defer self.mutex.unlock(self.io);
|
|
||||||
self.opts.limits = limits;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Applies new runner settings (heartbeat, timeout, retry codes) to jobs started from now on.
|
/// Applies new runner settings (heartbeat, timeout, retry codes) to jobs started from now on.
|
||||||
pub fn setRunnerOptions(self: *Scheduler, ro: runner.Options) void {
|
pub fn setRunnerOptions(self: *Scheduler, ro: runner.Options) void {
|
||||||
self.mutex.lockUncancelable(self.io);
|
self.mutex.lockUncancelable(self.io);
|
||||||
@@ -127,14 +110,6 @@ pub const Scheduler = struct {
|
|||||||
return self.opts.runner;
|
return self.opts.runner;
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn limitFor(self: *const Scheduler, level: LoadLevel) u32 {
|
|
||||||
return switch (level) {
|
|
||||||
.high => self.opts.limits.max_high_jobs,
|
|
||||||
.medium => self.opts.limits.max_medium_jobs,
|
|
||||||
.low => self.opts.limits.max_low_jobs,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
fn loop(self: *Scheduler) void {
|
fn loop(self: *Scheduler) void {
|
||||||
while (!self.stopping.load(.acquire)) {
|
while (!self.stopping.load(.acquire)) {
|
||||||
self.tick() catch |err| std.log.warn("scheduler tick failed: {s}", .{@errorName(err)});
|
self.tick() catch |err| std.log.warn("scheduler tick failed: {s}", .{@errorName(err)});
|
||||||
@@ -146,7 +121,8 @@ pub const Scheduler = struct {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One scheduling pass: starts every eligible queued job that fits its level's limit.
|
/// One scheduling pass: if no job is running, starts the next eligible queued job
|
||||||
|
/// (oldest first). Exactly one job runs at a time.
|
||||||
pub fn tick(self: *Scheduler) !void {
|
pub fn tick(self: *Scheduler) !void {
|
||||||
var arena_state = std.heap.ArenaAllocator.init(self.gpa);
|
var arena_state = std.heap.ArenaAllocator.init(self.gpa);
|
||||||
defer arena_state.deinit();
|
defer arena_state.deinit();
|
||||||
@@ -160,9 +136,12 @@ pub const Scheduler = struct {
|
|||||||
if (job.retry_at) |t| if (t > now) continue;
|
if (job.retry_at) |t| if (t > now) continue;
|
||||||
if (self.stopping.load(.acquire)) return;
|
if (self.stopping.load(.acquire)) return;
|
||||||
self.startJob(job) catch |err| switch (err) {
|
self.startJob(job) catch |err| switch (err) {
|
||||||
error.AtCapacity, error.AlreadyActive => continue,
|
// A job is already running (or this one is already tracked): wait for the
|
||||||
|
// next tick.
|
||||||
|
error.AtCapacity, error.AlreadyActive => return,
|
||||||
else => return err,
|
else => return err,
|
||||||
};
|
};
|
||||||
|
return; // one job runs at a time
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,21 +152,17 @@ pub const Scheduler = struct {
|
|||||||
const StartJobError = error{ AtCapacity, AlreadyActive } || Allocator.Error || std.Thread.SpawnError;
|
const StartJobError = error{ AtCapacity, AlreadyActive } || Allocator.Error || std.Thread.SpawnError;
|
||||||
|
|
||||||
fn startJob(self: *Scheduler, job: Job) StartJobError!void {
|
fn startJob(self: *Scheduler, job: Job) StartJobError!void {
|
||||||
const level = job.load_level;
|
|
||||||
const idx = @intFromEnum(level);
|
|
||||||
|
|
||||||
const entry = try self.gpa.create(Active);
|
const entry = try self.gpa.create(Active);
|
||||||
errdefer self.gpa.destroy(entry);
|
errdefer self.gpa.destroy(entry);
|
||||||
entry.* = .{ .id = try self.gpa.dupe(u8, job.id), .level = level };
|
entry.* = .{ .id = try self.gpa.dupe(u8, job.id) };
|
||||||
errdefer self.gpa.free(entry.id);
|
errdefer self.gpa.free(entry.id);
|
||||||
|
|
||||||
{
|
{
|
||||||
self.mutex.lockUncancelable(self.io);
|
self.mutex.lockUncancelable(self.io);
|
||||||
defer self.mutex.unlock(self.io);
|
defer self.mutex.unlock(self.io);
|
||||||
if (self.active.contains(job.id)) return error.AlreadyActive;
|
if (self.active.contains(job.id)) return error.AlreadyActive;
|
||||||
if (self.counts[idx] >= self.limitFor(level)) return error.AtCapacity;
|
if (self.active.count() >= 1) return error.AtCapacity;
|
||||||
try self.active.put(self.gpa, entry.id, entry);
|
try self.active.put(self.gpa, entry.id, entry);
|
||||||
self.counts[idx] += 1;
|
|
||||||
}
|
}
|
||||||
errdefer self.release(entry);
|
errdefer self.release(entry);
|
||||||
|
|
||||||
@@ -205,7 +180,6 @@ pub const Scheduler = struct {
|
|||||||
self.mutex.lockUncancelable(self.io);
|
self.mutex.lockUncancelable(self.io);
|
||||||
defer self.mutex.unlock(self.io);
|
defer self.mutex.unlock(self.io);
|
||||||
_ = self.active.remove(entry.id);
|
_ = self.active.remove(entry.id);
|
||||||
self.counts[@intFromEnum(entry.level)] -= 1;
|
|
||||||
}
|
}
|
||||||
self.gpa.free(entry.id);
|
self.gpa.free(entry.id);
|
||||||
self.gpa.destroy(entry);
|
self.gpa.destroy(entry);
|
||||||
@@ -305,25 +279,23 @@ test "runs queued jobs to completion" {
|
|||||||
try std.testing.expectEqual(@as(usize, 0), s.stop(2000));
|
try std.testing.expectEqual(@as(usize, 0), s.stop(2000));
|
||||||
}
|
}
|
||||||
|
|
||||||
test "load level limits cap concurrency and the rest wait their turn" {
|
test "only one job runs at a time and jobs finish in FIFO order" {
|
||||||
const env = try Env.init();
|
const env = try Env.init();
|
||||||
defer env.deinit();
|
defer env.deinit();
|
||||||
const a = env.arena.allocator();
|
const a = env.arena.allocator();
|
||||||
var ids: [3][]const u8 = undefined;
|
var ids: [3][]const u8 = undefined;
|
||||||
for (&ids) |*id| id.* = (try env.repo().create(a, &.{ "sleep", "0.4" }, .{ .load_level = .high })).id;
|
for (&ids) |*id| id.* = (try env.repo().create(a, &.{ "sleep", "0.3" }, .{})).id;
|
||||||
|
|
||||||
var opts = test_opts;
|
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), test_opts);
|
||||||
opts.limits = .{ .max_high_jobs = 1, .max_medium_jobs = 8, .max_low_jobs = 32 };
|
|
||||||
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), opts);
|
|
||||||
defer s.deinit();
|
defer s.deinit();
|
||||||
try s.start();
|
try s.start();
|
||||||
|
|
||||||
// While work remains, never more than one high job runs at a time.
|
// While work remains, never more than one job runs at a time.
|
||||||
var max_seen: u32 = 0;
|
var max_seen: usize = 0;
|
||||||
var done = false;
|
var done = false;
|
||||||
var waited: u64 = 0;
|
var waited: u64 = 0;
|
||||||
while (!done and waited < 8000) : (waited += 10) {
|
while (!done and waited < 10_000) : (waited += 10) {
|
||||||
max_seen = @max(max_seen, s.runningAt(.high));
|
max_seen = @max(max_seen, s.activeCount());
|
||||||
done = true;
|
done = true;
|
||||||
for (ids) |id| {
|
for (ids) |id| {
|
||||||
if ((try env.state(id)) != .succeeded) done = false;
|
if ((try env.state(id)) != .succeeded) done = false;
|
||||||
@@ -331,27 +303,19 @@ test "load level limits cap concurrency and the rest wait their turn" {
|
|||||||
try std.testing.io.sleep(.fromMilliseconds(10), .real);
|
try std.testing.io.sleep(.fromMilliseconds(10), .real);
|
||||||
}
|
}
|
||||||
try std.testing.expect(done);
|
try std.testing.expect(done);
|
||||||
try std.testing.expectEqual(@as(u32, 1), max_seen);
|
try std.testing.expectEqual(@as(usize, 1), max_seen);
|
||||||
_ = s.stop(2000);
|
|
||||||
}
|
|
||||||
|
|
||||||
test "different levels run concurrently" {
|
// FIFO: each job started only after the previous one finished.
|
||||||
const env = try Env.init();
|
var prev_finished: i128 = 0;
|
||||||
defer env.deinit();
|
for (ids) |id| {
|
||||||
const a = env.arena.allocator();
|
const job = (try env.repo().findById(a, id)).?;
|
||||||
const hi = try env.repo().create(a, &.{ "sleep", "0.6" }, .{ .load_level = .high });
|
try std.testing.expect(job.started_at != null and job.finished_at != null);
|
||||||
const lo = try env.repo().create(a, &.{ "sleep", "0.6" }, .{ .load_level = .low });
|
const started = job.started_at.?;
|
||||||
|
const finished = job.finished_at.?;
|
||||||
var opts = test_opts;
|
try std.testing.expect(started >= prev_finished);
|
||||||
opts.limits = .{ .max_high_jobs = 1, .max_medium_jobs = 1, .max_low_jobs = 1 };
|
try std.testing.expect(finished > started);
|
||||||
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), opts);
|
prev_finished = finished;
|
||||||
defer s.deinit();
|
}
|
||||||
try s.start();
|
|
||||||
try env.waitFor(hi.id, .running, 3000);
|
|
||||||
try env.waitFor(lo.id, .running, 3000);
|
|
||||||
try std.testing.expectEqual(@as(usize, 2), s.activeCount());
|
|
||||||
try env.waitFor(hi.id, .succeeded, 5000);
|
|
||||||
try env.waitFor(lo.id, .succeeded, 5000);
|
|
||||||
_ = s.stop(2000);
|
_ = s.stop(2000);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -407,22 +371,3 @@ test "only one scheduler per base dir" {
|
|||||||
try s2.start(); // lock released by stop
|
try s2.start(); // lock released by stop
|
||||||
_ = s2.stop(1000);
|
_ = s2.stop(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
test "limits can be changed while running" {
|
|
||||||
const env = try Env.init();
|
|
||||||
defer env.deinit();
|
|
||||||
const a = env.arena.allocator();
|
|
||||||
var opts = test_opts;
|
|
||||||
opts.limits = .{ .max_high_jobs = 1, .max_medium_jobs = 1, .max_low_jobs = 1 };
|
|
||||||
var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), opts);
|
|
||||||
defer s.deinit();
|
|
||||||
try s.start();
|
|
||||||
const j1 = try env.repo().create(a, &.{ "sleep", "0.8" }, .{});
|
|
||||||
const j2 = try env.repo().create(a, &.{ "sleep", "0.8" }, .{});
|
|
||||||
try env.waitFor(j1.id, .running, 3000);
|
|
||||||
try std.testing.io.sleep(.fromMilliseconds(150), .real);
|
|
||||||
try std.testing.expectEqual(State.queued, try env.state(j2.id)); // capped at 1
|
|
||||||
s.setLimits(.{ .max_high_jobs = 1, .max_medium_jobs = 2, .max_low_jobs = 1 });
|
|
||||||
try env.waitFor(j2.id, .running, 3000); // now allowed alongside j1
|
|
||||||
_ = s.stop(5000);
|
|
||||||
}
|
|
||||||
+8
-25
@@ -2,7 +2,7 @@
|
|||||||
//! IPC server together. Port of barn's `BarnService`.
|
//! IPC server together. Port of barn's `BarnService`.
|
||||||
//!
|
//!
|
||||||
//! Start order: directories, crash recovery, scheduler (takes the scheduler lock), IPC server,
|
//! Start order: directories, crash recovery, scheduler (takes the scheduler lock), IPC server,
|
||||||
//! cleanup timer. Stop order is the reverse. Configuration can be reloaded at runtime: limits,
|
//! cleanup timer. Stop order is the reverse. Configuration can be reloaded at runtime:
|
||||||
//! retry/timeout defaults, heartbeat and cleanup settings apply immediately; paths need a restart.
|
//! retry/timeout defaults, heartbeat and cleanup settings apply immediately; paths need a restart.
|
||||||
const std = @import("std");
|
const std = @import("std");
|
||||||
const Io = std.Io;
|
const Io = std.Io;
|
||||||
@@ -23,8 +23,6 @@ const duration = @import("duration.zig");
|
|||||||
const timestamp = @import("timestamp.zig");
|
const timestamp = @import("timestamp.zig");
|
||||||
const proc = @import("proc.zig");
|
const proc = @import("proc.zig");
|
||||||
const state_mod = @import("state.zig");
|
const state_mod = @import("state.zig");
|
||||||
const LoadLevel = @import("loadlevel.zig").LoadLevel;
|
|
||||||
const Classifier = @import("loadclass.zig").Classifier;
|
|
||||||
const Job = @import("job.zig").Job;
|
const Job = @import("job.zig").Job;
|
||||||
const Instant = @import("job.zig").Instant;
|
const Instant = @import("job.zig").Instant;
|
||||||
|
|
||||||
@@ -32,7 +30,6 @@ pub const ReloadFn = *const fn (ctx: ?*anyopaque, arena: Allocator) anyerror!con
|
|||||||
|
|
||||||
pub const Options = struct {
|
pub const Options = struct {
|
||||||
config: config.Config = .{},
|
config: config.Config = .{},
|
||||||
classifier: Classifier = .{},
|
|
||||||
reload_fn: ?ReloadFn = null,
|
reload_fn: ?ReloadFn = null,
|
||||||
reload_ctx: ?*anyopaque = null,
|
reload_ctx: ?*anyopaque = null,
|
||||||
scheduler_tick_ms: u64 = 1_000,
|
scheduler_tick_ms: u64 = 1_000,
|
||||||
@@ -101,7 +98,6 @@ pub const Service = struct {
|
|||||||
|
|
||||||
fn schedulerOptions(self: *Service, cfg: config.Config) scheduler_mod.Options {
|
fn schedulerOptions(self: *Service, cfg: config.Config) scheduler_mod.Options {
|
||||||
return .{
|
return .{
|
||||||
.limits = cfg.load_levels,
|
|
||||||
.tick_ms = self.opts.scheduler_tick_ms,
|
.tick_ms = self.opts.scheduler_tick_ms,
|
||||||
.runner = self.runnerOptions(cfg),
|
.runner = self.runnerOptions(cfg),
|
||||||
};
|
};
|
||||||
@@ -187,7 +183,6 @@ pub const Service = struct {
|
|||||||
self.cfg = new_cfg;
|
self.cfg = new_cfg;
|
||||||
self.cfg_mutex.unlock(self.io);
|
self.cfg_mutex.unlock(self.io);
|
||||||
|
|
||||||
self.scheduler.setLimits(new_cfg.load_levels);
|
|
||||||
self.scheduler.setRunnerOptions(self.runnerOptions(new_cfg));
|
self.scheduler.setRunnerOptions(self.runnerOptions(new_cfg));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,11 +305,6 @@ pub const Service = struct {
|
|||||||
if (req.payloadInt("timeoutSeconds")) |n| {
|
if (req.payloadInt("timeoutSeconds")) |n| {
|
||||||
create_opts.timeout_seconds = std.math.cast(u32, n) orelse return res.fail(.INVALID_REQUEST, "timeoutSeconds must be non-negative");
|
create_opts.timeout_seconds = std.math.cast(u32, n) orelse return res.fail(.INVALID_REQUEST, "timeoutSeconds must be non-negative");
|
||||||
}
|
}
|
||||||
create_opts.load_level = if (req.payloadString("loadLevel")) |l|
|
|
||||||
LoadLevel.parse(l) orelse return res.failFmt(.INVALID_REQUEST, "Invalid load level: '{s}'. Valid values are: high, medium, low", .{l})
|
|
||||||
else
|
|
||||||
self.opts.classifier.classify(command);
|
|
||||||
|
|
||||||
const job = try self.repo.create(res.arena, command, create_opts);
|
const job = try self.repo.create(res.arena, command, create_opts);
|
||||||
try jobjson.writeJob(&res.json, job);
|
try jobjson.writeJob(&res.json, job);
|
||||||
}
|
}
|
||||||
@@ -455,22 +445,15 @@ test "run a job end to end over IPC" {
|
|||||||
try std.testing.expect(status.get("pid").?.integer > 0);
|
try std.testing.expect(status.get("pid").?.integer > 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
test "load level is auto-classified or overridden" {
|
test "unknown loadLevel in a run_job payload is ignored" {
|
||||||
var classifier: Classifier = .{};
|
const h = try Harness.create(.{});
|
||||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
|
||||||
defer arena.deinit();
|
|
||||||
classifier = try Classifier.fromDefaults(arena.allocator());
|
|
||||||
const h = try Harness.create(.{ .classifier = classifier, .config = .{ .load_levels = .{ .max_high_jobs = 1, .max_medium_jobs = 1, .max_low_jobs = 1 } } });
|
|
||||||
defer h.destroy();
|
defer h.destroy();
|
||||||
|
|
||||||
const auto = try h.okObj("run_job", "{\"command\":[\"curl\",\"--version\"]}");
|
// Old clients (and pre-#2 zag) may still send a loadLevel; it is ignored, not an error.
|
||||||
try std.testing.expectEqualStrings("LOW", auto.get("loadLevel").?.string);
|
const job = try h.okObj("run_job", "{\"command\":[\"echo\",\"x\"],\"loadLevel\":\"high\"}");
|
||||||
const forced = try h.okObj("run_job", "{\"command\":[\"curl\",\"--version\"],\"loadLevel\":\"high\"}");
|
try std.testing.expectEqualStrings("QUEUED", job.get("state").?.string);
|
||||||
try std.testing.expectEqualStrings("HIGH", forced.get("loadLevel").?.string);
|
try std.testing.expect(job.get("loadLevel") == null);
|
||||||
const plain = try h.okObj("run_job", "{\"command\":[\"echo\",\"x\"]}");
|
try h.waitState(job.get("id").?.string, "SUCCEEDED");
|
||||||
try std.testing.expectEqualStrings("MEDIUM", plain.get("loadLevel").?.string);
|
|
||||||
const bad = try h.call("run_job", "{\"command\":[\"echo\"],\"loadLevel\":\"extreme\"}");
|
|
||||||
try std.testing.expectEqualStrings("INVALID_REQUEST", bad.err.code);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
test "request validation and not-found errors" {
|
test "request validation and not-found errors" {
|
||||||
|
|||||||
+37
-5
@@ -17,9 +17,11 @@ contains() { # contains <name> <needle> <haystack>
|
|||||||
}
|
}
|
||||||
json_field() { printf '%s\n' "$2" | sed -n "s/.*\"$1\" : \"\{0,1\}\([^\",]*\)\"\{0,1\},\{0,1\}\$/\1/p" | head -1; }
|
json_field() { printf '%s\n' "$2" | sed -n "s/.*\"$1\" : \"\{0,1\}\([^\",]*\)\"\{0,1\},\{0,1\}\$/\1/p" | head -1; }
|
||||||
wait_state() { # wait_state <id> <state> [seconds]
|
wait_state() { # wait_state <id> <state> [seconds]
|
||||||
local i
|
# ${2,,} would work on bash >= 4, but macOS ships bash 3.2
|
||||||
|
local lower i
|
||||||
|
lower=$(printf '%s' "$2" | tr '[:upper:]' '[:lower:]')
|
||||||
for ((i = 0; i < ${3:-100}; i++)); do
|
for ((i = 0; i < ${3:-100}; i++)); do
|
||||||
[[ $(json_field state "$(Z describe -o json "$1" --offline)") == "${2,,}" ]] && return 0
|
[[ $(json_field state "$(Z describe -o json "$1" --offline)") == "$lower" ]] && return 0
|
||||||
sleep 0.1
|
sleep 0.1
|
||||||
done
|
done
|
||||||
return 1
|
return 1
|
||||||
@@ -48,18 +50,26 @@ contains "clean --all removes it" "Cleaned 1 job" "$(Z clean --offline --all)"
|
|||||||
contains "status empty" "No jobs found." "$(Z status --offline)"
|
contains "status empty" "No jobs found." "$(Z status --offline)"
|
||||||
|
|
||||||
# --- config -----------------------------------------------------------------------------
|
# --- config -----------------------------------------------------------------------------
|
||||||
contains "config show --defaults" "max_high_jobs = 2" "$(Z config show --defaults)"
|
defaults_out=$(Z config show --defaults)
|
||||||
|
contains "config show --defaults" "retry_backoff_multiplier = 2.0" "$defaults_out"
|
||||||
|
case $defaults_out in *max_high_jobs*) fail "config show --defaults is free of load levels" ;; *) pass "config show --defaults is free of load levels" ;; esac
|
||||||
printf '[jobs]\nmax_retries = 0\nbogus = 1\n' >"$DIR/bad.conf"
|
printf '[jobs]\nmax_retries = 0\nbogus = 1\n' >"$DIR/bad.conf"
|
||||||
Z config validate --file "$DIR/bad.conf" >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "validate flags bad config" || fail "validate flags bad config"
|
Z config validate --file "$DIR/bad.conf" >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "validate flags bad config" || fail "validate flags bad config"
|
||||||
printf '[jobs]\nmax_retries = 0\n' >"$DIR/good.conf"
|
printf '[jobs]\nmax_retries = 0\n' >"$DIR/good.conf"
|
||||||
contains "validate accepts good config" "Configuration is valid" "$(Z config validate --file "$DIR/good.conf")"
|
contains "validate accepts good config" "Configuration is valid" "$(Z config validate --file "$DIR/good.conf")"
|
||||||
contains "install --show prints files" "high.load" "$(Z config install --show)"
|
printf '[service]\nmax_concurrent_jobs = 4\n[load_levels]\nmax_high_jobs = 2\n' >"$DIR/deprecated.conf"
|
||||||
|
deprecated_out=$(Z config validate --file "$DIR/deprecated.conf" 2>&1); rc=$?
|
||||||
|
[[ $rc -eq 0 ]] && contains "validate warns on deprecated settings, exit 0" "deprecated" "$deprecated_out" || fail "validate warns on deprecated settings (rc=$rc)"
|
||||||
|
contains "install --show prints files" "zag.conf" "$(Z config install --show)"
|
||||||
|
|
||||||
# --- daemon -----------------------------------------------------------------------------
|
# --- daemon -----------------------------------------------------------------------------
|
||||||
Z run echo hi >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "run without service exits 1" || fail "run without service exits 1"
|
Z run echo hi >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "run without service exits 1" || fail "run without service exits 1"
|
||||||
contains "service start" "Zag service started" "$(Z service start)"
|
# The daemon starts with the deprecated config: the removed settings must be ignored
|
||||||
|
# (effective config is the defaults) and its log must warn about them while it is running.
|
||||||
|
contains "service start" "Zag service started" "$("$ZAG" --barn-dir "$DIR" --config "$DIR/deprecated.conf" service start 2>&1)"
|
||||||
contains "second start refused" "already running" "$(Z service start 2>&1)"
|
contains "second start refused" "already running" "$(Z service start 2>&1)"
|
||||||
contains "service status running" "running" "$(Z service status)"
|
contains "service status running" "running" "$(Z service status)"
|
||||||
|
contains "daemon log warns on deprecated settings at startup" "deprecated" "$(cat "$DIR/logs/zag.log" 2>/dev/null)"
|
||||||
|
|
||||||
out=$(Z run -o json -t svc sh -c 'echo from-daemon')
|
out=$(Z run -o json -t svc sh -c 'echo from-daemon')
|
||||||
sid=$(json_field id "$out")
|
sid=$(json_field id "$out")
|
||||||
@@ -82,6 +92,28 @@ out=$(Z run -o json --timeout 1 sleep 30); tid=$(json_field id "$out")
|
|||||||
sleep 3
|
sleep 3
|
||||||
contains "timeout fails the job" '"exitCode" : "timeout"' "$(Z describe -o json "$tid" --offline)"
|
contains "timeout fails the job" '"exitCode" : "timeout"' "$(Z describe -o json "$tid" --offline)"
|
||||||
|
|
||||||
|
# Strict single-job FIFO: while the first job runs, the second stays queued, and both
|
||||||
|
# finish in creation order.
|
||||||
|
out=$(Z run -o json sleep 3); a1=$(json_field id "$out")
|
||||||
|
wait_state "$a1" RUNNING && pass "serial: first job is running" || fail "serial: first job is running"
|
||||||
|
out=$(Z run -o json sleep 1); b1=$(json_field id "$out")
|
||||||
|
contains "serial: second job stays queued" '"state" : "QUEUED"' "$out"
|
||||||
|
# The checks above would still pass if the scheduler ran both jobs concurrently
|
||||||
|
# (sleep 3 always finishes before sleep 1 started after it could catch up). Assert the
|
||||||
|
# defining FIFO invariant directly: b1 never leaves QUEUED while a1 is running.
|
||||||
|
exclusive=1
|
||||||
|
last=""
|
||||||
|
for i in 1 2 3 4 5 6 7 8 9 10 11 12; do
|
||||||
|
st_a=$(json_field state "$(Z describe -o json "$a1" --offline)")
|
||||||
|
[[ $st_a == "running" ]] || break
|
||||||
|
last=$(json_field state "$(Z describe -o json "$b1" --offline)")
|
||||||
|
[[ $last == "queued" ]] || exclusive=0
|
||||||
|
sleep 0.3
|
||||||
|
done
|
||||||
|
[[ $exclusive -eq 1 ]] && pass "serial: second job never runs while the first runs" || fail "serial: second job never runs while the first runs (state: $last)"
|
||||||
|
wait_state "$a1" SUCCEEDED && pass "serial: first job finishes first" || fail "serial: first job finishes first"
|
||||||
|
wait_state "$b1" SUCCEEDED && pass "serial: second job finishes second" || fail "serial: second job finishes second"
|
||||||
|
|
||||||
contains "service reload" "Configuration reloaded" "$(Z service reload)"
|
contains "service reload" "Configuration reloaded" "$(Z service reload)"
|
||||||
contains "clean via IPC" "Cleaned" "$(Z clean --all --include-failed)"
|
contains "clean via IPC" "Cleaned" "$(Z clean --all --include-failed)"
|
||||||
contains "service stop" "Zag service stopped" "$(Z service stop)"
|
contains "service stop" "Zag service stopped" "$(Z service stop)"
|
||||||
|
|||||||
Reference in new issue
Block a user