From f233547ce804dc3f4cea58fdbbdde1abaab3a94c Mon Sep 17 00:00:00 2001 From: Daniel Samson <12231216+daniel-samson@users.noreply.github.com> Date: Sat, 24 Jan 2026 14:17:40 +0000 Subject: [PATCH] feat(scheduler): add per-level job limits based on load classification Implements #34 - Job Limits Per Load Level Jobs are now classified into HIGH, MEDIUM, or LOW load levels based on gitignore-style whitelist files (.load files). This allows concurrent execution of different types of jobs (e.g., downloading while transcoding). Changes: - Add LoadLevel enum with default limits (HIGH=2, MEDIUM=8, LOW=32) - Add LoadLevelConfig record for per-level max jobs configuration - Add CommandMatcher sealed interface for matching commands by name/path/dir - Add LoadFileParser for parsing .load whitelist files - Add LoadLevelClassifier for auto-classifying commands - Add ConfigInstallCommand (barn config install) for default config files - Update JobScheduler to use per-level limits with EnumMap - Add --load-level/-l option to barn run for manual override - Add load level display to barn status and barn describe output - Remove --user flag from service install/uninstall (system-wide only) - Update documentation for load levels and whitelist files Default whitelists: - high.load: ffmpeg, ffprobe, handbrake, x264, x265, etc. - low.load: curl, wget, rclone, rsync, aria2c, etc. - medium.load: empty (unmatched commands default to MEDIUM) Co-Authored-By: Claude Opus 4.5 --- README.md | 75 ++++++- docs/config.md | 191 +++++++++++++++++- docs/jobs.md | 3 + .../samsonmedia/barn/cli/ConfigCommand.java | 3 +- .../barn/cli/ConfigInstallCommand.java | 123 +++++++++++ .../samsonmedia/barn/cli/HumanFormatter.java | 6 +- .../com/samsonmedia/barn/cli/RunCommand.java | 24 ++- .../barn/cli/ServiceInstallCommand.java | 43 ++-- .../barn/cli/ServiceUninstallCommand.java | 61 ++---- .../samsonmedia/barn/cli/StatusCommand.java | 7 +- .../barn/config/CommandMatcher.java | 116 +++++++++++ .../com/samsonmedia/barn/config/Config.java | 8 +- .../barn/config/ConfigDefaults.java | 38 ++++ .../samsonmedia/barn/config/ConfigLoader.java | 19 +- .../barn/config/LoadFileParser.java | 90 +++++++++ .../barn/config/LoadLevelConfig.java | 110 ++++++++++ .../samsonmedia/barn/execution/JobRunner.java | 2 +- .../barn/execution/JobScheduler.java | 149 +++++++++++--- .../java/com/samsonmedia/barn/jobs/Job.java | 46 ++++- .../samsonmedia/barn/jobs/JobManifest.java | 49 ++++- .../samsonmedia/barn/jobs/JobRepository.java | 31 ++- .../com/samsonmedia/barn/jobs/LoadLevel.java | 83 ++++++++ .../barn/jobs/LoadLevelClassifier.java | 142 +++++++++++++ .../samsonmedia/barn/service/BarnService.java | 27 ++- .../com.samsonmedia/barn/resource-config.json | 3 +- src/main/resources/defaults/barn.conf | 67 ++++++ src/main/resources/defaults/high.load | 16 ++ src/main/resources/defaults/low.load | 16 ++ src/main/resources/defaults/medium.load | 4 + .../barn/cli/ConfigCommandTest.java | 7 +- .../barn/cli/ConfigInstallCommandTest.java | 151 ++++++++++++++ .../barn/cli/HumanFormatterTest.java | 14 +- .../barn/cli/JsonFormatterTest.java | 4 +- .../barn/cli/ServiceInstallCommandTest.java | 4 +- .../barn/cli/XmlFormatterTest.java | 4 +- .../barn/config/CommandMatcherTest.java | 140 +++++++++++++ .../barn/config/ConfigLoaderTest.java | 45 +++++ .../samsonmedia/barn/config/ConfigTest.java | 23 ++- .../barn/config/LoadFileParserTest.java | 175 ++++++++++++++++ .../barn/config/LoadLevelConfigTest.java | 92 +++++++++ .../barn/execution/CrashRecoveryTest.java | 7 +- .../barn/execution/HeartbeatCheckerTest.java | 4 +- .../barn/execution/JobSchedulerTest.java | 55 ++++- .../barn/jobs/JobManifestTest.java | 25 +-- .../barn/jobs/JobRepositoryTest.java | 33 +++ .../com/samsonmedia/barn/jobs/JobTest.java | 38 +++- .../barn/jobs/LoadLevelClassifierTest.java | 149 ++++++++++++++ .../samsonmedia/barn/jobs/LoadLevelTest.java | 90 +++++++++ .../barn/jobs/RetryCalculatorTest.java | 7 +- .../barn/logging/JobContextTest.java | 4 +- .../barn/logging/JobLogEventsTest.java | 10 +- .../barn/service/BarnServiceTest.java | 4 +- 52 files changed, 2444 insertions(+), 193 deletions(-) create mode 100644 src/main/java/com/samsonmedia/barn/cli/ConfigInstallCommand.java create mode 100644 src/main/java/com/samsonmedia/barn/config/CommandMatcher.java create mode 100644 src/main/java/com/samsonmedia/barn/config/LoadFileParser.java create mode 100644 src/main/java/com/samsonmedia/barn/config/LoadLevelConfig.java create mode 100644 src/main/java/com/samsonmedia/barn/jobs/LoadLevel.java create mode 100644 src/main/java/com/samsonmedia/barn/jobs/LoadLevelClassifier.java create mode 100644 src/main/resources/defaults/barn.conf create mode 100644 src/main/resources/defaults/high.load create mode 100644 src/main/resources/defaults/low.load create mode 100644 src/main/resources/defaults/medium.load create mode 100644 src/test/java/com/samsonmedia/barn/cli/ConfigInstallCommandTest.java create mode 100644 src/test/java/com/samsonmedia/barn/config/CommandMatcherTest.java create mode 100644 src/test/java/com/samsonmedia/barn/config/LoadFileParserTest.java create mode 100644 src/test/java/com/samsonmedia/barn/config/LoadLevelConfigTest.java create mode 100644 src/test/java/com/samsonmedia/barn/jobs/LoadLevelClassifierTest.java create mode 100644 src/test/java/com/samsonmedia/barn/jobs/LoadLevelTest.java diff --git a/README.md b/README.md index 0015bd1..a91e0fc 100644 --- a/README.md +++ b/README.md @@ -143,12 +143,15 @@ barn service status This project creates a simple CLI commandlet with sub-comands. -- `barn service {start|stop|resart|reload|status|logs"}"` - manages the barn service +- `barn service {start|stop|restart|reload|status|logs}` - manages the barn service - `barn run {command}` - starts job - `barn status` - gets the status of all jobs running - `barn describe {jobId}` - collects all the info from /tmp and display it +- `barn usage {jobId}` - shows resource usage (CPU, memory, disk) for a job - `barn kill {jobId}` - kills a job - `barn clean` - performs clean up +- `barn config install` - installs default configuration files +- `barn config show` - shows effective configuration barn is just one binary for both the service and the client. the client uses IPC to communicate with the service. @@ -191,12 +194,13 @@ There needs to be a barn service in order to run jobs (unless you use --offline) ### Adding jobs -`barn run --output=json --tag=downloading }` takes in a command to run, starts a new process/thread, outputs the status of that job: +`barn run --output=json --tag=downloading ` takes in a command to run, starts a new process/thread, outputs the status of that job: -| File | Description | +| Field | Description | |---------------|--------------------------------------------------------| | `job_id` | the job of the job | | `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` | +| `load_level` | `HIGH`, `MEDIUM`, or `LOW` (auto-detected or manual) | | `tag` | user defined string | | `created_at` | Job creation timestamp | | `started_at` | Execution start timestamp | @@ -206,15 +210,18 @@ There needs to be a barn service in order to run jobs (unless you use --offline) | `pid` | OS process ID (best-effort) | | `heartbeat` | Last liveness update | -Users can tag job 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. -Developers can use the --offline command line option to test how the service behaves eg creating tmp files etc. This runs the same code as the service but without having to run the service +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}`. + +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. **Example: `barn run --output=json -- echo "Hello World"`** ```json { "id" : "job-6d368040", "state" : "QUEUED", + "loadLevel" : "MEDIUM", "command" : [ "echo", "Hello World" ], "tag" : null, "createdAt" : "2026-01-22T01:48:46.749629Z", @@ -236,12 +243,21 @@ Developers can use the --offline command line option to test how the service beh `barn status` gets the status of all jobs found in /tmp. +**Example: `barn status`** +``` +ID STATE LOAD TAG CREATED EXIT PID +job-6d368040 succeeded medium - 2026-01-22 01:48:46 0 17486 + +Total: 1 job (1 succeeded) +``` + **Example: `barn status --output=json`** ```json { "jobs" : [ { "id" : "job-6d368040", "state" : "SUCCEEDED", + "loadLevel" : "MEDIUM", "command" : [ "echo", "Hello World" ], "tag" : null, "createdAt" : "2026-01-22T01:48:46.739979Z", @@ -306,6 +322,55 @@ Developers can use the --offline command line option to test how the service beh ### Clean up jobs `barn clean` - removes completed jobs and cleans up old jobs (older than max_age config) from /tmp +--- + +## Load Levels + +Barn 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. + +### Load Level Types + +| 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/barn/`: + +- `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 + +Force a specific load level for a job: + +```bash +# Run ffmpeg as LOW load (bypass normal HIGH classification) +barn run --load-level=low -- ffmpeg -i input.mp4 output.mp4 + +# Run curl as HIGH load (override normal LOW classification) +barn run --load-level=high -- curl -O https://example.com/file.zip +``` + +### Installing Default Config + +Install default configuration files including load level whitelists: + +```bash +# Preview what would be installed +barn config install --show + +# Install to system config directory (requires sudo on Linux/macOS) +sudo barn config install --force +``` + +See [Configuration](docs/config.md) for detailed load level configuration options. + +--- ## Documentation diff --git a/docs/config.md b/docs/config.md index 7903b95..6bd61ca 100644 --- a/docs/config.md +++ b/docs/config.md @@ -6,13 +6,13 @@ This document describes the configuration file format and options for the Barn j ## Configuration File Location -Barn looks for configuration in the following locations (in order): +Barn uses system-wide configuration only: | Platform | Path | |----------|------| -| Linux | `/etc/barn/barn.conf` or `~/.config/barn/barn.conf` | -| macOS | `/etc/barn/barn.conf` or `~/Library/Application Support/barn/barn.conf` | -| Windows | `%PROGRAMDATA%\barn\barn.conf` or `%APPDATA%\barn\barn.conf` | +| Linux | `/etc/barn/barn.conf` | +| macOS | `/etc/barn/barn.conf` | +| Windows | `%PROGRAMDATA%\barn\barn.conf` | You can also specify a config file explicitly: @@ -29,10 +29,14 @@ Barn uses a simple key-value format (TOML-like): ```toml [service] log_level = "info" -max_concurrent_jobs = 4 heartbeat_interval_seconds = 5 ipc_socket = "/tmp/barn/barn.sock" +[load_levels] +max_high_jobs = 2 +max_medium_jobs = 8 +max_low_jobs = 32 + [jobs] default_timeout_seconds = 3600 max_retries = 3 @@ -57,13 +61,148 @@ max_disk_usage_gb = 50 | Key | Type | Default | Description | |-----|------|---------|-------------| | `log_level` | string | `"info"` | Logging verbosity: `debug`, `info`, `warn`, `error` | -| `max_concurrent_jobs` | integer | `4` | Maximum jobs running simultaneously | +| `max_concurrent_jobs` | integer | `4` | **Deprecated.** Use `[load_levels]` instead. | | `heartbeat_interval_seconds` | integer | `5` | How often running jobs update their heartbeat | | `ipc_socket` | string | platform-specific | Path to the IPC socket for CLI communication | | `stale_heartbeat_threshold_seconds` | integer | `30` | Heartbeat age before a job is considered orphaned | --- +## Load Level Settings + +Barn supports **per-level job limits** to allow concurrent execution of different types of jobs. For example, you can run multiple downloads (LOW load) while transcoding (HIGH load) without overwhelming the system. + +### Configuration + +```toml +[load_levels] +max_high_jobs = 2 +max_medium_jobs = 8 +max_low_jobs = 32 +``` + +| Key | Type | Default | Description | +|-----|------|---------|-------------| +| `max_high_jobs` | integer | `2` | Maximum concurrent HIGH load jobs (CPU/GPU intensive) | +| `max_medium_jobs` | integer | `8` | Maximum concurrent MEDIUM load jobs | +| `max_low_jobs` | integer | `32` | Maximum concurrent LOW load jobs (network/IO intensive) | + +### Load Level Classification + +Jobs are automatically classified into a load level based on **whitelist files** in the config directory. These files use a gitignore-style format. + +#### Whitelist File Locations + +| Platform | Directory | +|----------|-----------| +| Linux | `/etc/barn/` | +| macOS | `/etc/barn/` | +| Windows | `%PROGRAMDATA%\barn\` | + +#### Whitelist Files + +| File | Purpose | +|------|---------| +| `high.load` | CPU/GPU intensive commands (transcoding, encoding) | +| `medium.load` | General purpose commands | +| `low.load` | Network/IO intensive commands (downloads, uploads) | + +#### File Format + +``` +# Comments start with # +# Empty lines are ignored + +# Match by executable name (any path) +ffmpeg +curl + +# Match by full path +/usr/local/bin/custom-transcoder + +# Match any executable in a directory (trailing slash) +/opt/encoders/ +``` + +#### Example `high.load` + +``` +# High load commands - CPU/GPU intensive (transcoding, encoding) +# Maximum concurrent: 2 (default) +ffmpeg +ffprobe +handbrake +HandBrakeCLI +x264 +x265 +av1an +svt-av1 +``` + +#### Example `low.load` + +``` +# Low load commands - Network/IO intensive (downloads, uploads) +# Maximum concurrent: 32 (default) +curl +wget +rclone +rsync +aria2c +scp +sftp +cadaver +``` + +#### Classification Priority + +1. Commands are checked against HIGH whitelist first +2. Then MEDIUM whitelist +3. Then LOW whitelist +4. If no match, defaults to **MEDIUM** + +### Manual Load Level Override + +You can override the auto-detected load level per job: + +```bash +# Force a command to run as LOW load +barn run --load-level=low -- ffmpeg -i input.mp4 output.mp4 + +# Force a command to run as HIGH load +barn run --load-level=high -- curl -O https://example.com/file.zip +``` + +### Installing Default Config Files + +Use `barn config install` to create default configuration files: + +```bash +# Interactive installation (prompts for confirmation) +barn config install + +# Force installation without prompts +barn config install --force + +# Show what would be installed without writing +barn config install --show +``` + +This creates: +- `barn.conf` - Main configuration file +- `high.load` - High load whitelist (ffmpeg, etc.) +- `medium.load` - Medium load whitelist (empty) +- `low.load` - Low load whitelist (curl, wget, etc.) + +### Backward Compatibility + +When `[load_levels]` is not configured: +- The deprecated `max_concurrent_jobs` value is distributed proportionally across levels +- Ratio: 1 HIGH : 4 MEDIUM : 16 LOW +- Example: `max_concurrent_jobs = 21` → HIGH=1, MEDIUM=4, LOW=16 + +--- + ## Job Settings | Key | Type | Default | Description | @@ -251,7 +390,11 @@ Pattern: `BARN_
_` (uppercase, underscores) ```toml [service] log_level = "debug" -max_concurrent_jobs = 2 + +[load_levels] +max_high_jobs = 1 +max_medium_jobs = 2 +max_low_jobs = 4 [jobs] max_retries = 1 @@ -269,9 +412,13 @@ keep_failed_jobs = false ```toml [service] log_level = "warn" -max_concurrent_jobs = 8 heartbeat_interval_seconds = 10 +[load_levels] +max_high_jobs = 4 +max_medium_jobs = 16 +max_low_jobs = 64 + [jobs] max_retries = 5 retry_delay_seconds = 60 @@ -291,7 +438,12 @@ max_disk_usage_gb = 200 ```toml [service] -max_concurrent_jobs = 1 +log_level = "info" + +[load_levels] +max_high_jobs = 1 +max_medium_jobs = 1 +max_low_jobs = 1 [jobs] max_retries = 0 @@ -327,7 +479,24 @@ Settings that require a full restart: --- -## Validating Configuration +## Configuration Commands + +### Install Default Configuration + +Create default configuration files in the system config directory: + +```bash +# Interactive installation (prompts for confirmation) +barn config install + +# Install without prompts +barn config install --force + +# Preview what would be installed +barn config install --show +``` + +### Validate Configuration Check your config file for errors: @@ -336,6 +505,8 @@ barn config validate barn config validate --config /path/to/barn.conf ``` +### Show Configuration + Show effective configuration (with defaults and overrides): ```bash diff --git a/docs/jobs.md b/docs/jobs.md index 68a089a..63cdbce 100644 --- a/docs/jobs.md +++ b/docs/jobs.md @@ -78,6 +78,7 @@ Example: manifest.json state stage + load_level pid heartbeat exit_code @@ -121,6 +122,7 @@ Written once at job creation. |---------------|--------------------------------------------------------| | `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` | | `tag` | user defined string | +| `load_level` | `HIGH`, `MEDIUM`, or `LOW` (for scheduling priority) | | `created_at` | Job creation timestamp | | `started_at` | Execution start timestamp | | `finished_at` | Execution end timestamp | @@ -280,6 +282,7 @@ Contains daemon-level events, not job output. manifest.json state → running stage → transcode + load_level → HIGH pid → 12345 heartbeat → 2026-01-21T18:42:10Z started_at → 2026-01-21T18:40:01Z diff --git a/src/main/java/com/samsonmedia/barn/cli/ConfigCommand.java b/src/main/java/com/samsonmedia/barn/cli/ConfigCommand.java index 67bd511..0f8f375 100644 --- a/src/main/java/com/samsonmedia/barn/cli/ConfigCommand.java +++ b/src/main/java/com/samsonmedia/barn/cli/ConfigCommand.java @@ -16,7 +16,8 @@ import picocli.CommandLine.Spec; subcommands = { ConfigShowCommand.class, ConfigValidateCommand.class, - ConfigInitCommand.class + ConfigInitCommand.class, + ConfigInstallCommand.class } ) public class ConfigCommand implements Runnable { diff --git a/src/main/java/com/samsonmedia/barn/cli/ConfigInstallCommand.java b/src/main/java/com/samsonmedia/barn/cli/ConfigInstallCommand.java new file mode 100644 index 0000000..fcff815 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/cli/ConfigInstallCommand.java @@ -0,0 +1,123 @@ +package com.samsonmedia.barn.cli; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import com.samsonmedia.barn.config.ConfigDefaults; + +import picocli.CommandLine.Command; +import picocli.CommandLine.Option; + +/** + * Command to install default configuration files. + * + *

Installs barn.conf and load level whitelist files (high.load, medium.load, low.load) + * to the specified directory. By default, installs to the system config directory. + */ +@Command( + name = "install", + mixinStandardHelpOptions = true, + description = "Install default configuration files" +) +public class ConfigInstallCommand extends BaseCommand { + + private static final String DEFAULTS_PATH = "/defaults/"; + private static final List CONFIG_FILES = List.of( + "barn.conf", + "high.load", + "medium.load", + "low.load" + ); + + @Option(names = {"--directory", "-d"}, description = "Target directory for config files") + private Path targetDirectory; + + @Option(names = {"--force", "-f"}, description = "Skip confirmation and overwrite existing files") + private boolean force; + + @Option(names = {"--show"}, description = "Show what would be installed without writing") + private boolean showOnly; + + @Override + public Integer call() { + Path targetDir = targetDirectory != null + ? targetDirectory + : ConfigDefaults.getSystemConfigDir(); + + if (showOnly) { + return showWhatWouldBeInstalled(targetDir); + } + + if (!force) { + getOut().println("The following files will be created/overwritten:"); + for (String file : CONFIG_FILES) { + getOut().println(" " + targetDir.resolve(file)); + } + getOut().println(); + getOut().println("WARNING: This will overwrite any existing configuration."); + getOut().println("Use --force to proceed, or --show to preview without writing."); + return EXIT_SUCCESS; + } + + return installConfigFiles(targetDir); + } + + private Integer showWhatWouldBeInstalled(Path targetDir) { + getOut().println("Files that would be installed to: " + targetDir); + getOut().println(); + + for (String filename : CONFIG_FILES) { + getOut().println("=== " + filename + " ==="); + try { + String content = loadResourceFile(filename); + getOut().println(content); + getOut().println(); + } catch (IOException e) { + outputError("Failed to read resource: " + filename + " - " + e.getMessage()); + return EXIT_ERROR; + } + } + + return EXIT_SUCCESS; + } + + private Integer installConfigFiles(Path targetDir) { + try { + // Create target directory if needed + if (!Files.exists(targetDir)) { + Files.createDirectories(targetDir); + } + + for (String filename : CONFIG_FILES) { + Path targetPath = targetDir.resolve(filename); + String content = loadResourceFile(filename); + Files.writeString(targetPath, content); + getOut().println("Installed: " + targetPath); + } + + getOut().println(); + getOut().println("Configuration installed successfully."); + getOut().println("Config directory: " + targetDir); + + return EXIT_SUCCESS; + + } catch (IOException e) { + outputError("Failed to install configuration: " + e.getMessage()); + return EXIT_ERROR; + } + } + + private String loadResourceFile(String filename) throws IOException { + String resourcePath = DEFAULTS_PATH + filename; + try (InputStream is = ConfigInstallCommand.class.getResourceAsStream(resourcePath)) { + if (is == null) { + throw new IOException("Resource not found: " + resourcePath); + } + return new String(is.readAllBytes(), StandardCharsets.UTF_8); + } + } +} diff --git a/src/main/java/com/samsonmedia/barn/cli/HumanFormatter.java b/src/main/java/com/samsonmedia/barn/cli/HumanFormatter.java index dc00e18..85e9459 100644 --- a/src/main/java/com/samsonmedia/barn/cli/HumanFormatter.java +++ b/src/main/java/com/samsonmedia/barn/cli/HumanFormatter.java @@ -102,6 +102,7 @@ public class HumanFormatter implements OutputFormatter { StringBuilder sb = new StringBuilder(); sb.append(colorize("Job: ", BOLD)).append(job.id()).append("\n"); sb.append(" State: ").append(colorizeState(job.state())).append("\n"); + sb.append(" Load: ").append(job.loadLevel().toString().toLowerCase(Locale.ROOT)).append("\n"); sb.append(" Command: ").append(String.join(" ", job.command())).append("\n"); if (job.tag() != null) { @@ -139,7 +140,7 @@ public class HumanFormatter implements OutputFormatter { private String formatJobTable(List jobs) { // Define columns - List headers = List.of("ID", "STATE", "TAG", "CREATED", "EXIT"); + List headers = List.of("ID", "STATE", "LOAD", "TAG", "CREATED", "EXIT"); // Convert jobs to rows List> rows = new ArrayList<>(); @@ -147,6 +148,7 @@ public class HumanFormatter implements OutputFormatter { rows.add(List.of( job.id(), job.state().toString().toLowerCase(Locale.ROOT), + job.loadLevel().toString().toLowerCase(Locale.ROOT), job.tag() != null ? job.tag() : "-", formatTimestamp(job.createdAt()), job.exitCode() != null ? job.exitCode().toString() : "-" @@ -190,7 +192,7 @@ public class HumanFormatter implements OutputFormatter { // Apply colors based on column if (i == 1) { // STATE column cell = colorizeState(job.state(), cell); - } else if (i == 4 && !cell.trim().equals("-")) { // EXIT column + } else if (i == 5 && !cell.trim().equals("-")) { // EXIT column cell = colorizeExitCode(job.exitCode(), cell); } diff --git a/src/main/java/com/samsonmedia/barn/cli/RunCommand.java b/src/main/java/com/samsonmedia/barn/cli/RunCommand.java index 1b686c7..0ecc059 100644 --- a/src/main/java/com/samsonmedia/barn/cli/RunCommand.java +++ b/src/main/java/com/samsonmedia/barn/cli/RunCommand.java @@ -16,6 +16,8 @@ import com.samsonmedia.barn.ipc.IpcClient; import com.samsonmedia.barn.ipc.IpcException; import com.samsonmedia.barn.jobs.Job; import com.samsonmedia.barn.jobs.JobRepository; +import com.samsonmedia.barn.jobs.LoadLevel; +import com.samsonmedia.barn.jobs.LoadLevelClassifier; import com.samsonmedia.barn.logging.BarnLogger; import com.samsonmedia.barn.state.BarnDirectories; @@ -41,6 +43,10 @@ public class RunCommand extends BaseCommand { @Option(names = {"--tag", "-t"}, description = "Tag for filtering jobs") private String tag; + @Option(names = {"--load-level", "-l"}, + description = "Load level classification: ${COMPLETION-CANDIDATES} (default: auto-detect)") + private LoadLevel loadLevel; + @Option(names = {"--max-retries"}, description = "Override max retries") private Integer maxRetries; @@ -87,10 +93,19 @@ public class RunCommand extends BaseCommand { JobRepository repository = new JobRepository(dirs); JobsConfig jobsConfig = buildJobsConfig(); - // Create the job - Job job = repository.create(command, tag, jobsConfig); + // Determine load level: use explicit override, or auto-classify from whitelists + LoadLevel level; + if (loadLevel != null) { + level = loadLevel; + } else { + level = LoadLevelClassifier.loadFromConfigDir().classify(command); + LOG.debug("Auto-classified command as load level: {}", level); + } - LOG.info("Created job {} in offline mode", job.id()); + // Create the job + Job job = repository.create(command, tag, jobsConfig, level); + + LOG.info("Created job {} in offline mode with load level {}", job.id(), level); // Output job info in the appropriate format outputJobCreated(job); @@ -111,6 +126,9 @@ public class RunCommand extends BaseCommand { if (tag != null) { payload.put("tag", tag); } + if (loadLevel != null) { + payload.put("loadLevel", loadLevel.name()); + } if (maxRetries != null) { payload.put("maxRetries", maxRetries); } diff --git a/src/main/java/com/samsonmedia/barn/cli/ServiceInstallCommand.java b/src/main/java/com/samsonmedia/barn/cli/ServiceInstallCommand.java index 13fd120..1116591 100644 --- a/src/main/java/com/samsonmedia/barn/cli/ServiceInstallCommand.java +++ b/src/main/java/com/samsonmedia/barn/cli/ServiceInstallCommand.java @@ -19,10 +19,12 @@ import picocli.CommandLine.Option; * *

Supports platform-specific service installation: *

    - *
  • macOS: launchd (LaunchDaemons/LaunchAgents)
  • - *
  • Linux: systemd (planned)
  • - *
  • Windows: Windows Service (planned)
  • + *
  • macOS: launchd (LaunchDaemons)
  • + *
  • Linux: systemd
  • + *
  • Windows: Windows Service
  • *
+ * + *

System-wide installation requires root/administrator privileges. */ @Command( name = "install", @@ -33,9 +35,6 @@ public class ServiceInstallCommand extends BaseCommand { private static final BarnLogger LOG = BarnLogger.getLogger(ServiceInstallCommand.class); - @Option(names = {"--user"}, description = "Install as user service instead of system-wide") - private boolean userService; - @Option(names = {"--barn-dir"}, description = "Barn data directory") private Path barnDir; @@ -72,12 +71,11 @@ public class ServiceInstallCommand extends BaseCommand { // Generate and write plist String plistContent = launchd.generatePlist(effectiveBinaryPath, effectiveBarnDir); - Path plistPath = userService ? launchd.getUserAgentPath() : launchd.getSystemDaemonPath(); + Path plistPath = launchd.getSystemDaemonPath(); // Check if we need sudo for system-wide installation - if (!userService && !canWriteToPath(plistPath.getParent())) { - outputError("System-wide installation requires root privileges. " - + "Run with sudo or use --user for user-level installation."); + if (!canWriteToPath(plistPath.getParent())) { + outputError("System-wide installation requires root privileges. Run with sudo."); return EXIT_ERROR; } @@ -86,10 +84,9 @@ public class ServiceInstallCommand extends BaseCommand { // Load the service launchd.load(plistPath); - String serviceType = userService ? "user agent" : "system daemon"; - getOut().println("Barn installed as macOS " + serviceType); + getOut().println("Barn installed as macOS system daemon"); getOut().println("Plist location: " + plistPath); - getOut().println("Service will start automatically on login/boot."); + getOut().println("Service will start automatically on boot."); getOut().println(); getOut().println("To start now: barn service start"); getOut().println("To uninstall: barn service uninstall"); @@ -114,7 +111,7 @@ public class ServiceInstallCommand extends BaseCommand { SystemdManager systemd = new SystemdManager(); // Check if already installed - Path unitPath = userService ? systemd.getUserServicePath() : systemd.getSystemServicePath(); + Path unitPath = systemd.getSystemServicePath(); if (Files.exists(unitPath)) { outputError("Barn service is already installed. Use 'barn service uninstall' first."); return EXIT_ERROR; @@ -128,24 +125,22 @@ public class ServiceInstallCommand extends BaseCommand { Files.createDirectories(effectiveBarnDir); Files.createDirectories(effectiveBarnDir.resolve("logs")); - // Generate and write unit file - String unitContent = systemd.generateUnitFile(effectiveBinaryPath, effectiveBarnDir, userService); + // Generate and write unit file (system-wide, not user) + String unitContent = systemd.generateUnitFile(effectiveBinaryPath, effectiveBarnDir, false); // Check if we need sudo for system-wide installation - if (!userService && !canWriteToPath(unitPath.getParent())) { - outputError("System-wide installation requires root privileges. " - + "Run with sudo or use --user for user-level installation."); + if (!canWriteToPath(unitPath.getParent())) { + outputError("System-wide installation requires root privileges. Run with sudo."); return EXIT_ERROR; } systemd.writeUnitFile(unitPath, unitContent); - // Reload systemd and enable the service - systemd.daemonReload(userService); - systemd.enable(userService); + // Reload systemd and enable the service (system-wide) + systemd.daemonReload(false); + systemd.enable(false); - String serviceType = userService ? "user service" : "system service"; - getOut().println("Barn installed as Linux " + serviceType); + getOut().println("Barn installed as Linux system service"); getOut().println("Unit file: " + unitPath); getOut().println("Service will start automatically on boot."); getOut().println(); diff --git a/src/main/java/com/samsonmedia/barn/cli/ServiceUninstallCommand.java b/src/main/java/com/samsonmedia/barn/cli/ServiceUninstallCommand.java index f187b22..9f18dea 100644 --- a/src/main/java/com/samsonmedia/barn/cli/ServiceUninstallCommand.java +++ b/src/main/java/com/samsonmedia/barn/cli/ServiceUninstallCommand.java @@ -18,9 +18,11 @@ import picocli.CommandLine.Option; *

Removes platform-specific service registration: *

    *
  • macOS: launchd plist files
  • - *
  • Linux: systemd unit files (planned)
  • - *
  • Windows: Windows Service registration (planned)
  • + *
  • Linux: systemd unit files
  • + *
  • Windows: Windows Service registration
  • *
+ * + *

System-wide uninstallation requires root/administrator privileges. */ @Command( name = "uninstall", @@ -31,9 +33,6 @@ public class ServiceUninstallCommand extends BaseCommand { private static final BarnLogger LOG = BarnLogger.getLogger(ServiceUninstallCommand.class); - @Option(names = {"--user"}, description = "Uninstall user service instead of system-wide") - private boolean userService; - @Option(names = {"--force"}, description = "Force uninstall even if service is running") private boolean force; @@ -51,27 +50,17 @@ public class ServiceUninstallCommand extends BaseCommand { private int uninstallMacOs() { LaunchdManager launchd = new LaunchdManager(); - Path plistPath = userService ? launchd.getUserAgentPath() : launchd.getSystemDaemonPath(); + Path plistPath = launchd.getSystemDaemonPath(); // Check if installed if (!Files.exists(plistPath)) { - if (userService) { - // Try system daemon if user service not found - Path systemPath = launchd.getSystemDaemonPath(); - if (Files.exists(systemPath)) { - getOut().println("No user service found, but system daemon exists."); - getOut().println("Run without --user to uninstall system daemon."); - return EXIT_ERROR; - } - } outputError("Barn service is not installed"); return EXIT_ERROR; } // Check if we need sudo for system-wide uninstallation - if (!userService && !canWriteToPath(plistPath)) { - outputError("System-wide uninstallation requires root privileges. " - + "Run with sudo or use --user for user-level service."); + if (!canWriteToPath(plistPath)) { + outputError("System-wide uninstallation requires root privileges. Run with sudo."); return EXIT_ERROR; } @@ -98,8 +87,7 @@ public class ServiceUninstallCommand extends BaseCommand { } } - String serviceType = userService ? "user agent" : "system daemon"; - getOut().println("Barn " + serviceType + " uninstalled successfully"); + getOut().println("Barn system daemon uninstalled successfully"); getOut().println("Removed: " + plistPath); return EXIT_SUCCESS; @@ -117,35 +105,25 @@ public class ServiceUninstallCommand extends BaseCommand { } SystemdManager systemd = new SystemdManager(); - Path unitPath = userService ? systemd.getUserServicePath() : systemd.getSystemServicePath(); + Path unitPath = systemd.getSystemServicePath(); // Check if installed if (!Files.exists(unitPath)) { - if (userService) { - // Try system service if user service not found - Path systemPath = systemd.getSystemServicePath(); - if (Files.exists(systemPath)) { - getOut().println("No user service found, but system service exists."); - getOut().println("Run without --user to uninstall system service."); - return EXIT_ERROR; - } - } outputError("Barn service is not installed"); return EXIT_ERROR; } // Check if we need sudo for system-wide uninstallation - if (!userService && !canWriteToPath(unitPath)) { - outputError("System-wide uninstallation requires root privileges. " - + "Run with sudo or use --user for user-level service."); + if (!canWriteToPath(unitPath)) { + outputError("System-wide uninstallation requires root privileges. Run with sudo."); return EXIT_ERROR; } try { - // Stop and disable the service first - if (systemd.isActive(userService)) { + // Stop and disable the service first (system-wide) + if (systemd.isActive(false)) { try { - systemd.stop(userService); + systemd.stop(false); } catch (SystemdManager.SystemdException e) { if (!force) { outputError("Failed to stop service: " + e.getMessage() @@ -156,9 +134,9 @@ public class ServiceUninstallCommand extends BaseCommand { } } - if (systemd.isEnabled(userService)) { + if (systemd.isEnabled(false)) { try { - systemd.disable(userService); + systemd.disable(false); } catch (SystemdManager.SystemdException e) { LOG.warn("Failed to disable service: {}", e.getMessage()); } @@ -172,15 +150,14 @@ public class ServiceUninstallCommand extends BaseCommand { } } - // Reload systemd + // Reload systemd (system-wide) try { - systemd.daemonReload(userService); + systemd.daemonReload(false); } catch (SystemdManager.SystemdException e) { LOG.warn("Failed to reload systemd: {}", e.getMessage()); } - String serviceType = userService ? "user service" : "system service"; - getOut().println("Barn " + serviceType + " uninstalled successfully"); + getOut().println("Barn system service uninstalled successfully"); getOut().println("Removed: " + unitPath); return EXIT_SUCCESS; diff --git a/src/main/java/com/samsonmedia/barn/cli/StatusCommand.java b/src/main/java/com/samsonmedia/barn/cli/StatusCommand.java index e682f79..d10c761 100644 --- a/src/main/java/com/samsonmedia/barn/cli/StatusCommand.java +++ b/src/main/java/com/samsonmedia/barn/cli/StatusCommand.java @@ -195,14 +195,15 @@ public class StatusCommand extends BaseCommand { .max().orElse(3)); // Header - sb.append(String.format("%-" + idWidth + "s %-9s %-" + tagWidth + "s %-19s %-4s %-8s%n", - "ID", "STATE", "TAG", "CREATED", "EXIT", "PID")); + sb.append(String.format("%-" + idWidth + "s %-9s %-6s %-" + tagWidth + "s %-19s %-4s %-8s%n", + "ID", "STATE", "LOAD", "TAG", "CREATED", "EXIT", "PID")); // Rows for (Job job : jobs) { - sb.append(String.format("%-" + idWidth + "s %-9s %-" + tagWidth + "s %-19s %-4s %-8s%n", + sb.append(String.format("%-" + idWidth + "s %-9s %-6s %-" + tagWidth + "s %-19s %-4s %-8s%n", job.id(), job.state().toString().toLowerCase(Locale.ROOT), + job.loadLevel().toString().toLowerCase(Locale.ROOT), job.tag() != null ? job.tag() : "-", formatTimestamp(job.createdAt()), job.exitCode() != null ? job.exitCode().toString() : "-", diff --git a/src/main/java/com/samsonmedia/barn/config/CommandMatcher.java b/src/main/java/com/samsonmedia/barn/config/CommandMatcher.java new file mode 100644 index 0000000..423a2f5 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/config/CommandMatcher.java @@ -0,0 +1,116 @@ +package com.samsonmedia.barn.config; + +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; + +/** + * Matches commands against load level whitelist entries. + * + *

Commands can be matched by: + *

    + *
  • Executable name only (e.g., "ffmpeg")
  • + *
  • Full path to executable (e.g., "/usr/local/bin/ffmpeg")
  • + *
  • Directory containing executables (e.g., "/opt/encoders/")
  • + *
+ */ +public sealed interface CommandMatcher { + + /** + * Checks if this matcher matches the given command. + * + * @param command the command and arguments (first element is the executable) + * @return true if this matcher matches the command + */ + boolean matches(List command); + + /** + * Matches commands by executable name only. + * + *

The executable name is extracted from the command path and compared. + * For example, "ffmpeg" matches both "ffmpeg" and "/usr/bin/ffmpeg". + * + * @param name the executable name to match (without path) + */ + record ExecutableName(String name) implements CommandMatcher { + + /** + * Creates an ExecutableName matcher with validation. + */ + public ExecutableName { + Objects.requireNonNull(name, "name must not be null"); + if (name.isBlank()) { + throw new IllegalArgumentException("name must not be blank"); + } + } + + @Override + public boolean matches(List command) { + if (command.isEmpty()) { + return false; + } + String executable = command.getFirst(); + Path fileName = Path.of(executable).getFileName(); + if (fileName == null) { + return false; + } + return name.equals(fileName.toString()); + } + } + + /** + * Matches commands by exact full path. + * + *

The command must exactly match the specified path. + * + * @param path the full path to match + */ + record FullPath(Path path) implements CommandMatcher { + + /** + * Creates a FullPath matcher with validation. + */ + public FullPath { + Objects.requireNonNull(path, "path must not be null"); + } + + @Override + public boolean matches(List command) { + if (command.isEmpty()) { + return false; + } + return Path.of(command.getFirst()).equals(path); + } + } + + /** + * Matches commands whose executables are in the specified directory. + * + *

Subdirectories are not matched. + * + * @param directory the directory containing executables + */ + record Directory(Path directory) implements CommandMatcher { + + /** + * Creates a Directory matcher with validation. + */ + public Directory { + Objects.requireNonNull(directory, "directory must not be null"); + } + + @Override + public boolean matches(List command) { + if (command.isEmpty()) { + return false; + } + Path commandPath = Path.of(command.getFirst()); + Path parent = commandPath.getParent(); + if (parent == null) { + return false; + } + // Normalize both paths for comparison + return parent.normalize().equals(directory.normalize()); + } + } +} diff --git a/src/main/java/com/samsonmedia/barn/config/Config.java b/src/main/java/com/samsonmedia/barn/config/Config.java index d2dd974..260a0c4 100644 --- a/src/main/java/com/samsonmedia/barn/config/Config.java +++ b/src/main/java/com/samsonmedia/barn/config/Config.java @@ -9,12 +9,14 @@ import java.util.Objects; * @param jobs job execution configuration * @param cleanup automatic cleanup configuration * @param storage storage and filesystem configuration + * @param loadLevels per-load-level job limits configuration */ public record Config( ServiceConfig service, JobsConfig jobs, CleanupConfig cleanup, - StorageConfig storage + StorageConfig storage, + LoadLevelConfig loadLevels ) { /** @@ -25,6 +27,7 @@ public record Config( Objects.requireNonNull(jobs, "jobs must not be null"); Objects.requireNonNull(cleanup, "cleanup must not be null"); Objects.requireNonNull(storage, "storage must not be null"); + Objects.requireNonNull(loadLevels, "loadLevels must not be null"); } /** @@ -37,7 +40,8 @@ public record Config( ServiceConfig.withDefaults(), JobsConfig.withDefaults(), CleanupConfig.withDefaults(), - StorageConfig.withDefaults() + StorageConfig.withDefaults(), + LoadLevelConfig.withDefaults() ); } } diff --git a/src/main/java/com/samsonmedia/barn/config/ConfigDefaults.java b/src/main/java/com/samsonmedia/barn/config/ConfigDefaults.java index 1b3030c..babb256 100644 --- a/src/main/java/com/samsonmedia/barn/config/ConfigDefaults.java +++ b/src/main/java/com/samsonmedia/barn/config/ConfigDefaults.java @@ -77,6 +77,44 @@ public final class ConfigDefaults { }; } + /** + * Gets the system-wide configuration directory path. + * + * @return the system config directory + */ + public static Path getSystemConfigDir() { + return switch (OperatingSystem.current()) { + case WINDOWS -> { + String programData = System.getenv("PROGRAMDATA"); + if (programData == null || programData.isBlank()) { + programData = "C:\\ProgramData"; + } + yield Path.of(programData, "barn"); + } + case LINUX, MACOS -> Path.of("/etc/barn"); + }; + } + + /** + * Gets the user-specific configuration directory path. + * + * @return the user config directory + */ + public static Path getUserConfigDir() { + String userHome = System.getProperty("user.home", ""); + return switch (OperatingSystem.current()) { + case WINDOWS -> { + String appData = System.getenv("APPDATA"); + if (appData == null || appData.isBlank()) { + appData = Path.of(userHome, "AppData", "Roaming").toString(); + } + yield Path.of(appData, "barn"); + } + case MACOS -> Path.of(userHome, "Library", "Application Support", "barn"); + case LINUX -> Path.of(userHome, ".config", "barn"); + }; + } + /** * Gets the list of configuration file paths in priority order. * diff --git a/src/main/java/com/samsonmedia/barn/config/ConfigLoader.java b/src/main/java/com/samsonmedia/barn/config/ConfigLoader.java index 00b079d..f36abdd 100644 --- a/src/main/java/com/samsonmedia/barn/config/ConfigLoader.java +++ b/src/main/java/com/samsonmedia/barn/config/ConfigLoader.java @@ -186,11 +186,17 @@ public final class ConfigLoader { } private Config buildConfig(Map> data) { + // Handle both "load_levels" (from TOML) and "loadlevels" (from env vars) + Map loadLevelData = data.getOrDefault("load_levels", Map.of()); + if (loadLevelData.isEmpty()) { + loadLevelData = data.getOrDefault("loadlevels", Map.of()); + } return new Config( buildServiceConfig(data.getOrDefault("service", Map.of())), buildJobsConfig(data.getOrDefault("jobs", Map.of())), buildCleanupConfig(data.getOrDefault("cleanup", Map.of())), - buildStorageConfig(data.getOrDefault("storage", Map.of())) + buildStorageConfig(data.getOrDefault("storage", Map.of())), + buildLoadLevelConfig(loadLevelData) ); } @@ -250,6 +256,17 @@ public final class ConfigLoader { ); } + private LoadLevelConfig buildLoadLevelConfig(Map data) { + return new LoadLevelConfig( + getOrDefault(data, "max_high_jobs", LoadLevelConfig.DEFAULT_MAX_HIGH_JOBS, + this::toInt), + getOrDefault(data, "max_medium_jobs", LoadLevelConfig.DEFAULT_MAX_MEDIUM_JOBS, + this::toInt), + getOrDefault(data, "max_low_jobs", LoadLevelConfig.DEFAULT_MAX_LOW_JOBS, + this::toInt) + ); + } + @SuppressWarnings("unchecked") private T getOrDefault(Map data, String key, T defaultValue, Function converter) { diff --git a/src/main/java/com/samsonmedia/barn/config/LoadFileParser.java b/src/main/java/com/samsonmedia/barn/config/LoadFileParser.java new file mode 100644 index 0000000..9732d35 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/config/LoadFileParser.java @@ -0,0 +1,90 @@ +package com.samsonmedia.barn.config; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +/** + * Parses load level whitelist files (.load files). + * + *

Load files use a gitignore-like format: + *

    + *
  • Lines starting with # are comments
  • + *
  • Empty lines are ignored
  • + *
  • Plain names (e.g., "ffmpeg") match any executable with that name
  • + *
  • Full paths (e.g., "/usr/bin/ffmpeg") match that exact path
  • + *
  • Directories with trailing slash (e.g., "/opt/encoders/") match any executable in that directory
  • + *
+ */ +public final class LoadFileParser { + + private LoadFileParser() { + // Utility class + } + + /** + * Parses a load file into a list of command matchers. + * + * @param path the path to the load file + * @return a list of matchers, in file order + * @throws IOException if the file cannot be read + */ + public static List parse(Path path) throws IOException { + Objects.requireNonNull(path, "path must not be null"); + + List lines = Files.readAllLines(path); + List matchers = new ArrayList<>(); + + for (String line : lines) { + String trimmed = line.strip(); + + // Skip comments and empty lines + if (trimmed.isEmpty() || trimmed.startsWith("#")) { + continue; + } + + matchers.add(createMatcher(trimmed)); + } + + return matchers; + } + + /** + * Parses a load file if it exists, otherwise returns an empty list. + * + * @param path the path to the load file + * @return a list of matchers, or empty list if file doesn't exist + */ + public static List parseIfExists(Path path) { + Objects.requireNonNull(path, "path must not be null"); + + if (!Files.exists(path)) { + return List.of(); + } + + try { + return parse(path); + } catch (IOException e) { + // Log and return empty list for robustness + return List.of(); + } + } + + private static CommandMatcher createMatcher(String entry) { + // Directory matcher: ends with / + if (entry.endsWith("/")) { + return new CommandMatcher.Directory(Path.of(entry)); + } + + // Full path matcher: contains path separator + if (entry.contains("/")) { + return new CommandMatcher.FullPath(Path.of(entry)); + } + + // Executable name matcher: just a name + return new CommandMatcher.ExecutableName(entry); + } +} diff --git a/src/main/java/com/samsonmedia/barn/config/LoadLevelConfig.java b/src/main/java/com/samsonmedia/barn/config/LoadLevelConfig.java new file mode 100644 index 0000000..16b2844 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/config/LoadLevelConfig.java @@ -0,0 +1,110 @@ +package com.samsonmedia.barn.config; + +import java.util.Objects; + +import com.samsonmedia.barn.jobs.LoadLevel; + +/** + * Configuration for per-load-level job limits. + * + *

This configuration controls how many jobs of each load level can run + * concurrently. This allows the system to run many lightweight tasks (like + * file downloads) while limiting resource-intensive tasks (like transcoding). + * + * @param maxHighJobs maximum concurrent high load jobs + * @param maxMediumJobs maximum concurrent medium load jobs + * @param maxLowJobs maximum concurrent low load jobs + */ +public record LoadLevelConfig( + int maxHighJobs, + int maxMediumJobs, + int maxLowJobs +) { + + /** Default maximum high load jobs. */ + public static final int DEFAULT_MAX_HIGH_JOBS = LoadLevel.HIGH.getDefaultMaxJobs(); + + /** Default maximum medium load jobs. */ + public static final int DEFAULT_MAX_MEDIUM_JOBS = LoadLevel.MEDIUM.getDefaultMaxJobs(); + + /** Default maximum low load jobs. */ + public static final int DEFAULT_MAX_LOW_JOBS = LoadLevel.LOW.getDefaultMaxJobs(); + + /** + * Creates a LoadLevelConfig with validation. + */ + public LoadLevelConfig { + if (maxHighJobs < 1) { + throw new IllegalArgumentException("maxHighJobs must be at least 1"); + } + if (maxMediumJobs < 1) { + throw new IllegalArgumentException("maxMediumJobs must be at least 1"); + } + if (maxLowJobs < 1) { + throw new IllegalArgumentException("maxLowJobs must be at least 1"); + } + } + + /** + * Creates a LoadLevelConfig with default values. + * + * @return a LoadLevelConfig with all defaults + */ + public static LoadLevelConfig withDefaults() { + return new LoadLevelConfig( + DEFAULT_MAX_HIGH_JOBS, + DEFAULT_MAX_MEDIUM_JOBS, + DEFAULT_MAX_LOW_JOBS + ); + } + + /** + * Creates a LoadLevelConfig from a total limit (for backward compatibility). + * + *

Distributes the total limit proportionally based on default ratios: + * HIGH gets ~5%, MEDIUM gets ~19%, LOW gets ~76% (matching default 2:8:32 ratio). + * + * @param totalLimit the total maximum concurrent jobs + * @return a LoadLevelConfig with proportional limits + * @deprecated Use explicit per-level limits instead + */ + @Deprecated + public static LoadLevelConfig fromTotalLimit(int totalLimit) { + if (totalLimit < 3) { + // Minimum: 1 for each level + return new LoadLevelConfig(1, 1, 1); + } + + // Use default ratio of 2:8:32 = 1:4:16 + int totalRatio = 1 + 4 + 16; // 21 + int high = Math.max(1, (totalLimit * 1) / totalRatio); + int medium = Math.max(1, (totalLimit * 4) / totalRatio); + int low = Math.max(1, totalLimit - high - medium); + + return new LoadLevelConfig(high, medium, low); + } + + /** + * Returns the maximum concurrent jobs for the specified load level. + * + * @param level the load level + * @return the maximum concurrent jobs for that level + */ + public int getMaxJobsFor(LoadLevel level) { + Objects.requireNonNull(level, "level must not be null"); + return switch (level) { + case HIGH -> maxHighJobs; + case MEDIUM -> maxMediumJobs; + case LOW -> maxLowJobs; + }; + } + + /** + * Returns the total maximum concurrent jobs across all levels. + * + * @return the sum of all level limits + */ + public int getTotalMaxJobs() { + return maxHighJobs + maxMediumJobs + maxLowJobs; + } +} diff --git a/src/main/java/com/samsonmedia/barn/execution/JobRunner.java b/src/main/java/com/samsonmedia/barn/execution/JobRunner.java index 37e4a54..9fe5686 100644 --- a/src/main/java/com/samsonmedia/barn/execution/JobRunner.java +++ b/src/main/java/com/samsonmedia/barn/execution/JobRunner.java @@ -209,7 +209,7 @@ public class JobRunner { job.id(), job.state(), job.command(), job.tag(), job.createdAt(), job.startedAt(), job.finishedAt(), exitCode, job.error(), job.pid(), job.heartbeat(), - job.retryCount(), job.retryAt() + job.retryCount(), job.retryAt(), job.loadLevel() ); return retryCalculator.shouldRetry(jobWithExitCode); } diff --git a/src/main/java/com/samsonmedia/barn/execution/JobScheduler.java b/src/main/java/com/samsonmedia/barn/execution/JobScheduler.java index 5e2f0d2..917b8f2 100644 --- a/src/main/java/com/samsonmedia/barn/execution/JobScheduler.java +++ b/src/main/java/com/samsonmedia/barn/execution/JobScheduler.java @@ -4,7 +4,9 @@ import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.Comparator; +import java.util.EnumMap; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.concurrent.ExecutorService; @@ -15,8 +17,10 @@ import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import com.samsonmedia.barn.config.Config; +import com.samsonmedia.barn.config.LoadLevelConfig; import com.samsonmedia.barn.jobs.Job; import com.samsonmedia.barn.jobs.JobRepository; +import com.samsonmedia.barn.jobs.LoadLevel; import com.samsonmedia.barn.logging.BarnLogger; import com.samsonmedia.barn.state.BarnDirectories; import com.samsonmedia.barn.state.JobState; @@ -36,12 +40,12 @@ public class JobScheduler { private final JobRepository repository; private final JobRunner runner; private final BarnDirectories dirs; - private final int maxConcurrentJobs; + private final LoadLevelConfig loadLevelConfig; private final Duration pollInterval; private final Duration shutdownTimeout; private final AtomicBoolean running = new AtomicBoolean(false); - private final AtomicInteger runningJobCount = new AtomicInteger(0); + private final Map runningJobCounts; private ExecutorService jobExecutor; private ScheduledExecutorService schedulerThread; @@ -61,13 +65,17 @@ public class JobScheduler { BarnDirectories dirs, Config config) { this(repository, runner, dirs, - config.service().maxConcurrentJobs(), + config.loadLevels(), DEFAULT_POLL_INTERVAL, DEFAULT_SHUTDOWN_TIMEOUT); } /** - * Creates a JobScheduler with custom settings. + * Creates a JobScheduler with custom settings using legacy single-limit mode. + * + *

In legacy mode, all jobs are treated as MEDIUM load level, and the + * maxConcurrentJobs limit applies only to MEDIUM jobs. HIGH and LOW levels + * use their default limits. * * @param repository the job repository * @param runner the job runner @@ -75,7 +83,9 @@ public class JobScheduler { * @param maxConcurrentJobs the maximum number of concurrent jobs * @param pollInterval the interval between queue checks * @param shutdownTimeout the maximum time to wait for shutdown + * @deprecated Use the constructor with LoadLevelConfig instead */ + @Deprecated public JobScheduler( JobRepository repository, JobRunner runner, @@ -83,19 +93,49 @@ public class JobScheduler { int maxConcurrentJobs, Duration pollInterval, Duration shutdownTimeout) { + this(repository, runner, dirs, + createLegacyConfig(maxConcurrentJobs), + pollInterval, + shutdownTimeout); + } + + private static LoadLevelConfig createLegacyConfig(int maxConcurrentJobs) { + if (maxConcurrentJobs <= 0) { + throw new IllegalArgumentException("maxConcurrentJobs must be positive: " + maxConcurrentJobs); + } + // In legacy mode, apply limit to MEDIUM only, use minimum for others + return new LoadLevelConfig(1, maxConcurrentJobs, 1); + } + + /** + * Creates a JobScheduler with per-level limits. + * + * @param repository the job repository + * @param runner the job runner + * @param dirs the directory manager + * @param loadLevelConfig the per-level job limits + * @param pollInterval the interval between queue checks + * @param shutdownTimeout the maximum time to wait for shutdown + */ + public JobScheduler( + JobRepository repository, + JobRunner runner, + BarnDirectories dirs, + LoadLevelConfig loadLevelConfig, + Duration pollInterval, + Duration shutdownTimeout) { this.repository = Objects.requireNonNull(repository, "repository must not be null"); this.runner = Objects.requireNonNull(runner, "runner must not be null"); this.dirs = Objects.requireNonNull(dirs, "dirs must not be null"); - this.maxConcurrentJobs = validatePositive(maxConcurrentJobs, "maxConcurrentJobs"); + this.loadLevelConfig = Objects.requireNonNull(loadLevelConfig, "loadLevelConfig must not be null"); this.pollInterval = Objects.requireNonNull(pollInterval, "pollInterval must not be null"); this.shutdownTimeout = Objects.requireNonNull(shutdownTimeout, "shutdownTimeout must not be null"); - } - private static int validatePositive(int value, String name) { - if (value <= 0) { - throw new IllegalArgumentException(name + " must be positive: " + value); + // Initialize per-level running job counts + this.runningJobCounts = new EnumMap<>(LoadLevel.class); + for (LoadLevel level : LoadLevel.values()) { + runningJobCounts.put(level, new AtomicInteger(0)); } - return value; } /** @@ -118,8 +158,10 @@ public class JobScheduler { } lock = acquired.get(); + int totalMaxJobs = loadLevelConfig.getTotalMaxJobs(); + // Create executors - jobExecutor = Executors.newFixedThreadPool(maxConcurrentJobs, r -> { + jobExecutor = Executors.newFixedThreadPool(totalMaxJobs, r -> { Thread t = new Thread(r, "job-executor"); t.setDaemon(true); return t; @@ -141,7 +183,11 @@ public class JobScheduler { TimeUnit.MILLISECONDS ); - LOG.info("Scheduler started with max {} concurrent jobs", maxConcurrentJobs); + LOG.info("Scheduler started with per-level limits: HIGH={}, MEDIUM={}, LOW={} (total={})", + loadLevelConfig.maxHighJobs(), + loadLevelConfig.maxMediumJobs(), + loadLevelConfig.maxLowJobs(), + totalMaxJobs); } /** @@ -241,11 +287,21 @@ public class JobScheduler { LOG.warn("Failed to count queued jobs: {}", e.getMessage()); } + int totalRunning = runningJobCounts.values().stream() + .mapToInt(AtomicInteger::get) + .sum(); + return new SchedulerStatus( - runningJobCount.get(), + totalRunning, queuedCount, - maxConcurrentJobs, - running.get() + loadLevelConfig.getTotalMaxJobs(), + running.get(), + runningJobCounts.get(LoadLevel.HIGH).get(), + runningJobCounts.get(LoadLevel.MEDIUM).get(), + runningJobCounts.get(LoadLevel.LOW).get(), + loadLevelConfig.maxHighJobs(), + loadLevelConfig.maxMediumJobs(), + loadLevelConfig.maxLowJobs() ); } @@ -264,64 +320,91 @@ public class JobScheduler { } try { - // Check if we have capacity - int currentRunning = runningJobCount.get(); - if (currentRunning >= maxConcurrentJobs) { - return; - } - - // Find next queued job - Optional nextJob = findNextQueued(); + // Find next queued job that has capacity in its load level + Optional nextJob = findNextQueuedWithCapacity(); if (nextJob.isEmpty()) { return; } Job job = nextJob.get(); + LoadLevel level = job.loadLevel(); // Check if job is ready (not scheduled for later retry) if (job.retryAt() != null && job.retryAt().isAfter(Instant.now())) { return; } - // Increment count and submit - runningJobCount.incrementAndGet(); + // Increment count for this level and submit + runningJobCounts.get(level).incrementAndGet(); jobExecutor.submit(() -> { try { runner.run(job); } finally { - runningJobCount.decrementAndGet(); + runningJobCounts.get(level).decrementAndGet(); } }); - LOG.debug("Scheduled job: {}", job.id()); + LOG.debug("Scheduled job: {} (level={})", job.id(), level); } catch (IOException e) { LOG.error("Error in scheduler: {}", e.getMessage(), e); } } - private Optional findNextQueued() throws IOException { + private Optional findNextQueuedWithCapacity() throws IOException { List queuedJobs = repository.findByState(JobState.QUEUED); - // Sort by creation time (FIFO) + // Sort by creation time (FIFO) and filter by retry time and capacity return queuedJobs.stream() .filter(job -> job.retryAt() == null || !job.retryAt().isAfter(Instant.now())) + .filter(this::hasCapacityForLevel) .min(Comparator.comparing(Job::createdAt)); } + private boolean hasCapacityForLevel(Job job) { + LoadLevel level = job.loadLevel(); + int currentRunning = runningJobCounts.get(level).get(); + int maxForLevel = loadLevelConfig.getMaxJobsFor(level); + return currentRunning < maxForLevel; + } + /** * Status of the job scheduler. * - * @param runningJobs the number of currently running jobs + * @param runningJobs the total number of currently running jobs * @param queuedJobs the number of queued jobs - * @param maxConcurrentJobs the maximum concurrent job limit + * @param maxConcurrentJobs the total maximum concurrent job limit * @param isRunning whether the scheduler is running + * @param runningHighJobs running HIGH load level jobs + * @param runningMediumJobs running MEDIUM load level jobs + * @param runningLowJobs running LOW load level jobs + * @param maxHighJobs maximum HIGH load level jobs + * @param maxMediumJobs maximum MEDIUM load level jobs + * @param maxLowJobs maximum LOW load level jobs */ public record SchedulerStatus( int runningJobs, int queuedJobs, int maxConcurrentJobs, - boolean isRunning - ) { } + boolean isRunning, + int runningHighJobs, + int runningMediumJobs, + int runningLowJobs, + int maxHighJobs, + int maxMediumJobs, + int maxLowJobs + ) { + /** + * Creates a SchedulerStatus with only legacy fields (for backward compatibility). + * + * @param runningJobs the total number of currently running jobs + * @param queuedJobs the number of queued jobs + * @param maxConcurrentJobs the total maximum concurrent job limit + * @param isRunning whether the scheduler is running + */ + public SchedulerStatus(int runningJobs, int queuedJobs, int maxConcurrentJobs, boolean isRunning) { + this(runningJobs, queuedJobs, maxConcurrentJobs, isRunning, 0, 0, 0, 0, 0, 0); + } + } } diff --git a/src/main/java/com/samsonmedia/barn/jobs/Job.java b/src/main/java/com/samsonmedia/barn/jobs/Job.java index 8a85027..27758db 100644 --- a/src/main/java/com/samsonmedia/barn/jobs/Job.java +++ b/src/main/java/com/samsonmedia/barn/jobs/Job.java @@ -25,6 +25,7 @@ import com.samsonmedia.barn.state.JobState; * @param heartbeat last liveness check timestamp * @param retryCount current retry attempt (0-based) * @param retryAt when to retry (null if not scheduled for retry) + * @param loadLevel the load level classification for this job */ public record Job( String id, @@ -39,7 +40,8 @@ public record Job( Long pid, Instant heartbeat, int retryCount, - Instant retryAt + Instant retryAt, + LoadLevel loadLevel ) { /** @@ -50,6 +52,7 @@ public record Job( Objects.requireNonNull(state, "state must not be null"); Objects.requireNonNull(command, "command must not be null"); Objects.requireNonNull(createdAt, "createdAt must not be null"); + Objects.requireNonNull(loadLevel, "loadLevel must not be null"); if (id.isBlank()) { throw new IllegalArgumentException("id must not be blank"); } @@ -68,9 +71,22 @@ public record Job( * @param id the job ID * @param command the command to execute * @param tag optional tag (may be null) - * @return a new Job in QUEUED state + * @return a new Job in QUEUED state with MEDIUM load level */ public static Job createQueued(String id, List command, String tag) { + return createQueued(id, command, tag, LoadLevel.getDefault()); + } + + /** + * Creates a new queued job with specified load level. + * + * @param id the job ID + * @param command the command to execute + * @param tag optional tag (may be null) + * @param loadLevel the load level for this job + * @return a new Job in QUEUED state + */ + public static Job createQueued(String id, List command, String tag, LoadLevel loadLevel) { return new Job( id, JobState.QUEUED, @@ -84,7 +100,8 @@ public record Job( null, // pid null, // heartbeat 0, // retryCount - null // retryAt + null, // retryAt + loadLevel ); } @@ -96,7 +113,18 @@ public record Job( */ public Job withState(JobState newState) { return new Job(id, newState, command, tag, createdAt, startedAt, finishedAt, - exitCode, error, pid, heartbeat, retryCount, retryAt); + exitCode, error, pid, heartbeat, retryCount, retryAt, loadLevel); + } + + /** + * Creates a copy of this job with a new load level. + * + * @param newLoadLevel the new load level + * @return a new Job with the updated load level + */ + public Job withLoadLevel(LoadLevel newLoadLevel) { + return new Job(id, state, command, tag, createdAt, startedAt, finishedAt, + exitCode, error, pid, heartbeat, retryCount, retryAt, newLoadLevel); } /** @@ -108,7 +136,7 @@ public record Job( public Job withStarted(long processId) { Instant now = Instant.now(); return new Job(id, JobState.RUNNING, command, tag, createdAt, now, finishedAt, - exitCode, error, processId, now, retryCount, retryAt); + exitCode, error, processId, now, retryCount, retryAt, loadLevel); } /** @@ -121,7 +149,7 @@ public record Job( public Job withCompleted(int code, String errorMessage) { JobState newState = (code == 0) ? JobState.SUCCEEDED : JobState.FAILED; return new Job(id, newState, command, tag, createdAt, startedAt, Instant.now(), - code, errorMessage, pid, heartbeat, retryCount, retryAt); + code, errorMessage, pid, heartbeat, retryCount, retryAt, loadLevel); } /** @@ -132,7 +160,7 @@ public record Job( */ public Job withHeartbeat(Instant timestamp) { return new Job(id, state, command, tag, createdAt, startedAt, finishedAt, - exitCode, error, pid, timestamp, retryCount, retryAt); + exitCode, error, pid, timestamp, retryCount, retryAt, loadLevel); } /** @@ -143,7 +171,7 @@ public record Job( */ public Job withRetry(Instant retryTimestamp) { return new Job(id, JobState.QUEUED, command, tag, createdAt, null, null, - null, null, null, null, retryCount + 1, retryTimestamp); + null, null, null, null, retryCount + 1, retryTimestamp, loadLevel); } /** @@ -153,7 +181,7 @@ public record Job( */ public Job withCanceled() { return new Job(id, JobState.CANCELED, command, tag, createdAt, startedAt, Instant.now(), - exitCode, "Job was canceled", pid, heartbeat, retryCount, retryAt); + exitCode, "Job was canceled", pid, heartbeat, retryCount, retryAt, loadLevel); } /** diff --git a/src/main/java/com/samsonmedia/barn/jobs/JobManifest.java b/src/main/java/com/samsonmedia/barn/jobs/JobManifest.java index 8352618..7ecf478 100644 --- a/src/main/java/com/samsonmedia/barn/jobs/JobManifest.java +++ b/src/main/java/com/samsonmedia/barn/jobs/JobManifest.java @@ -19,6 +19,7 @@ import com.samsonmedia.barn.config.JobsConfig; * @param maxRetries maximum number of retry attempts * @param retryDelaySeconds initial delay before first retry * @param retryBackoffMultiplier multiplier for exponential backoff + * @param loadLevel the load level classification for this job */ public record JobManifest( String id, @@ -27,7 +28,8 @@ public record JobManifest( Instant createdAt, int maxRetries, int retryDelaySeconds, - double retryBackoffMultiplier + double retryBackoffMultiplier, + LoadLevel loadLevel ) { /** @@ -37,6 +39,7 @@ public record JobManifest( Objects.requireNonNull(id, "id must not be null"); Objects.requireNonNull(command, "command must not be null"); Objects.requireNonNull(createdAt, "createdAt must not be null"); + Objects.requireNonNull(loadLevel, "loadLevel must not be null"); if (id.isBlank()) { throw new IllegalArgumentException("id must not be blank"); } @@ -62,9 +65,24 @@ public record JobManifest( * @param command the command to execute * @param tag optional tag (may be null) * @param config the jobs configuration for defaults - * @return a new JobManifest + * @return a new JobManifest with MEDIUM load level */ public static JobManifest create(String id, List command, String tag, JobsConfig config) { + return create(id, command, tag, config, LoadLevel.getDefault()); + } + + /** + * Creates a JobManifest with default retry configuration from JobsConfig. + * + * @param id the job ID + * @param command the command to execute + * @param tag optional tag (may be null) + * @param config the jobs configuration for defaults + * @param loadLevel the load level for this job + * @return a new JobManifest + */ + public static JobManifest create(String id, List command, String tag, + JobsConfig config, LoadLevel loadLevel) { Objects.requireNonNull(config, "config must not be null"); return new JobManifest( id, @@ -73,7 +91,8 @@ public record JobManifest( Instant.now(), config.maxRetries(), config.retryDelaySeconds(), - config.retryBackoffMultiplier() + config.retryBackoffMultiplier(), + loadLevel ); } @@ -86,10 +105,29 @@ public record JobManifest( * @param maxRetries maximum retry attempts * @param retryDelaySeconds initial retry delay * @param retryBackoffMultiplier backoff multiplier - * @return a new JobManifest + * @return a new JobManifest with MEDIUM load level */ public static JobManifest create(String id, List command, String tag, int maxRetries, int retryDelaySeconds, double retryBackoffMultiplier) { + return create(id, command, tag, maxRetries, retryDelaySeconds, retryBackoffMultiplier, + LoadLevel.getDefault()); + } + + /** + * Creates a JobManifest with custom retry configuration and load level. + * + * @param id the job ID + * @param command the command to execute + * @param tag optional tag (may be null) + * @param maxRetries maximum retry attempts + * @param retryDelaySeconds initial retry delay + * @param retryBackoffMultiplier backoff multiplier + * @param loadLevel the load level for this job + * @return a new JobManifest + */ + public static JobManifest create(String id, List command, String tag, + int maxRetries, int retryDelaySeconds, double retryBackoffMultiplier, + LoadLevel loadLevel) { return new JobManifest( id, command, @@ -97,7 +135,8 @@ public record JobManifest( Instant.now(), maxRetries, retryDelaySeconds, - retryBackoffMultiplier + retryBackoffMultiplier, + loadLevel ); } diff --git a/src/main/java/com/samsonmedia/barn/jobs/JobRepository.java b/src/main/java/com/samsonmedia/barn/jobs/JobRepository.java index 0c4f216..9ac682f 100644 --- a/src/main/java/com/samsonmedia/barn/jobs/JobRepository.java +++ b/src/main/java/com/samsonmedia/barn/jobs/JobRepository.java @@ -53,7 +53,7 @@ public class JobRepository { } /** - * Creates a new job with the given command and configuration. + * Creates a new job with the given command and configuration using default load level. * * @param command the command to execute * @param tag optional user tag (may be null) @@ -62,11 +62,27 @@ public class JobRepository { * @throws IOException if creation fails */ public Job create(List command, String tag, JobsConfig config) throws IOException { + return create(command, tag, config, LoadLevel.getDefault()); + } + + /** + * Creates a new job with the given command, configuration, and load level. + * + * @param command the command to execute + * @param tag optional user tag (may be null) + * @param config the jobs configuration for defaults + * @param loadLevel the load level classification for this job + * @return the created Job + * @throws IOException if creation fails + */ + public Job create(List command, String tag, JobsConfig config, LoadLevel loadLevel) + throws IOException { Objects.requireNonNull(command, "command must not be null"); Objects.requireNonNull(config, "config must not be null"); + Objects.requireNonNull(loadLevel, "loadLevel must not be null"); String id = JobIdGenerator.generate(); - JobManifest manifest = JobManifest.create(id, command, tag, config); + JobManifest manifest = JobManifest.create(id, command, tag, config, loadLevel); // Create directories dirs.createJobDirs(id); @@ -86,7 +102,7 @@ public class JobRepository { stateFiles.writeRetryCount(0); LOG.info("Created job: {}", id); - return Job.createQueued(id, command, tag); + return Job.createQueued(id, command, tag, loadLevel); } /** @@ -388,6 +404,12 @@ public class JobRepository { StateFiles stateFiles = new StateFiles(jobDir); JobManifest manifest = loadManifest(id); + // For backward compatibility, use manifest's loadLevel (which defaults to MEDIUM) + // if no loadLevel field exists in manifest (old jobs) + LoadLevel loadLevel = manifest.loadLevel() != null + ? manifest.loadLevel() + : LoadLevel.getDefault(); + return new Job( id, stateFiles.readState().orElse(JobState.QUEUED), @@ -401,7 +423,8 @@ public class JobRepository { stateFiles.readPid().isPresent() ? stateFiles.readPid().getAsLong() : null, stateFiles.readHeartbeat().orElse(null), stateFiles.readRetryCount().orElse(0), - stateFiles.readRetryAt().orElse(null) + stateFiles.readRetryAt().orElse(null), + loadLevel ); } } diff --git a/src/main/java/com/samsonmedia/barn/jobs/LoadLevel.java b/src/main/java/com/samsonmedia/barn/jobs/LoadLevel.java new file mode 100644 index 0000000..ed68f68 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/jobs/LoadLevel.java @@ -0,0 +1,83 @@ +package com.samsonmedia.barn.jobs; + +import java.util.Locale; + +/** + * Load level classification for jobs. + * + *

Jobs are classified into load levels based on their resource intensity: + *

    + *
  • {@link #HIGH} - CPU/GPU intensive tasks like transcoding (default: 2 concurrent)
  • + *
  • {@link #MEDIUM} - General purpose tasks (default: 8 concurrent)
  • + *
  • {@link #LOW} - Network/IO intensive tasks like downloads (default: 32 concurrent)
  • + *
+ */ +public enum LoadLevel { + + /** + * High load level for CPU/GPU intensive tasks (e.g., ffmpeg, transcoding). + */ + HIGH(2), + + /** + * Medium load level for general purpose tasks. + */ + MEDIUM(8), + + /** + * Low load level for network/IO intensive tasks (e.g., curl, rclone). + */ + LOW(32); + + private final int defaultMaxJobs; + + LoadLevel(int defaultMaxJobs) { + this.defaultMaxJobs = defaultMaxJobs; + } + + /** + * Returns the default maximum concurrent jobs for this load level. + * + * @return the default max jobs + */ + public int getDefaultMaxJobs() { + return defaultMaxJobs; + } + + /** + * Returns the lowercase string representation of this load level. + * + * @return the lowercase string + */ + public String toLowercase() { + return name().toLowerCase(Locale.ROOT); + } + + /** + * Returns the default load level (MEDIUM). + * + * @return the default load level + */ + public static LoadLevel getDefault() { + return MEDIUM; + } + + /** + * Parses a load level from a string (case-insensitive). + * + * @param value the string value to parse + * @return the parsed LoadLevel + * @throws IllegalArgumentException if the value is not a valid load level + */ + public static LoadLevel fromString(String value) { + if (value == null || value.isBlank()) { + throw new IllegalArgumentException("Load level cannot be null or blank"); + } + try { + return valueOf(value.trim().toUpperCase(Locale.ROOT)); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + "Invalid load level: '" + value + "'. Valid values are: high, medium, low"); + } + } +} diff --git a/src/main/java/com/samsonmedia/barn/jobs/LoadLevelClassifier.java b/src/main/java/com/samsonmedia/barn/jobs/LoadLevelClassifier.java new file mode 100644 index 0000000..d094922 --- /dev/null +++ b/src/main/java/com/samsonmedia/barn/jobs/LoadLevelClassifier.java @@ -0,0 +1,142 @@ +package com.samsonmedia.barn.jobs; + +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; + +import com.samsonmedia.barn.config.CommandMatcher; +import com.samsonmedia.barn.config.ConfigDefaults; +import com.samsonmedia.barn.config.LoadFileParser; + +/** + * Classifies commands into load levels based on whitelist files. + * + *

The classifier loads whitelist files from the config directory: + *

    + *
  • {@code high.load} - Commands that are CPU/GPU intensive (e.g., transcoding)
  • + *
  • {@code medium.load} - General purpose commands
  • + *
  • {@code low.load} - Commands that are network/IO intensive (e.g., downloads)
  • + *
+ * + *

Commands are matched against each list in priority order: HIGH, MEDIUM, LOW. + * If a command is not matched by any list, it defaults to MEDIUM. + */ +public final class LoadLevelClassifier { + + /** File name for high load whitelist. */ + public static final String HIGH_LOAD_FILE = "high.load"; + + /** File name for medium load whitelist. */ + public static final String MEDIUM_LOAD_FILE = "medium.load"; + + /** File name for low load whitelist. */ + public static final String LOW_LOAD_FILE = "low.load"; + + private final List highMatchers; + private final List mediumMatchers; + private final List lowMatchers; + + /** + * Creates a LoadLevelClassifier with the given matchers. + * + * @param highMatchers matchers for HIGH load level + * @param mediumMatchers matchers for MEDIUM load level + * @param lowMatchers matchers for LOW load level + */ + public LoadLevelClassifier( + List highMatchers, + List mediumMatchers, + List lowMatchers) { + this.highMatchers = List.copyOf(Objects.requireNonNull(highMatchers, "highMatchers")); + this.mediumMatchers = List.copyOf(Objects.requireNonNull(mediumMatchers, "mediumMatchers")); + this.lowMatchers = List.copyOf(Objects.requireNonNull(lowMatchers, "lowMatchers")); + } + + /** + * Loads a classifier from whitelist files in the specified directory. + * + *

If a whitelist file doesn't exist, an empty list is used for that level. + * + * @param configDir the directory containing whitelist files + * @return a new classifier + */ + public static LoadLevelClassifier load(Path configDir) { + Objects.requireNonNull(configDir, "configDir must not be null"); + + List high = LoadFileParser.parseIfExists(configDir.resolve(HIGH_LOAD_FILE)); + List medium = LoadFileParser.parseIfExists(configDir.resolve(MEDIUM_LOAD_FILE)); + List low = LoadFileParser.parseIfExists(configDir.resolve(LOW_LOAD_FILE)); + + return new LoadLevelClassifier(high, medium, low); + } + + /** + * Loads a classifier from the system config directory. + * + *

Searches for whitelist files in the system config directory + * (e.g., /etc/barn/ on Linux/macOS, %PROGRAMDATA%\barn\ on Windows). + * + *

If no config directory is found, returns a classifier with empty whitelists + * (all commands default to MEDIUM). + * + * @return a new classifier + */ + public static LoadLevelClassifier loadFromConfigDir() { + Path systemConfig = ConfigDefaults.getSystemConfigDir(); + if (Files.isDirectory(systemConfig) && hasAnyLoadFile(systemConfig)) { + return load(systemConfig); + } + + // Return empty classifier (all commands default to MEDIUM) + return new LoadLevelClassifier(List.of(), List.of(), List.of()); + } + + private static boolean hasAnyLoadFile(Path dir) { + return Files.exists(dir.resolve(HIGH_LOAD_FILE)) + || Files.exists(dir.resolve(MEDIUM_LOAD_FILE)) + || Files.exists(dir.resolve(LOW_LOAD_FILE)); + } + + /** + * Classifies a command into a load level. + * + *

Commands are checked against each whitelist in priority order: + * HIGH, MEDIUM, LOW. If a command matches multiple lists, the highest + * priority level wins. If no match is found, MEDIUM is returned. + * + * @param command the command and arguments (first element is the executable) + * @return the load level for this command + */ + public LoadLevel classify(List command) { + Objects.requireNonNull(command, "command must not be null"); + + if (command.isEmpty()) { + return LoadLevel.getDefault(); + } + + // Check HIGH first (highest priority) + for (CommandMatcher matcher : highMatchers) { + if (matcher.matches(command)) { + return LoadLevel.HIGH; + } + } + + // Check MEDIUM second + for (CommandMatcher matcher : mediumMatchers) { + if (matcher.matches(command)) { + return LoadLevel.MEDIUM; + } + } + + // Check LOW third + for (CommandMatcher matcher : lowMatchers) { + if (matcher.matches(command)) { + return LoadLevel.LOW; + } + } + + // Default to MEDIUM + return LoadLevel.getDefault(); + } +} diff --git a/src/main/java/com/samsonmedia/barn/service/BarnService.java b/src/main/java/com/samsonmedia/barn/service/BarnService.java index 4588c5b..5822550 100644 --- a/src/main/java/com/samsonmedia/barn/service/BarnService.java +++ b/src/main/java/com/samsonmedia/barn/service/BarnService.java @@ -21,6 +21,8 @@ import com.samsonmedia.barn.ipc.IpcException; import com.samsonmedia.barn.ipc.IpcServer; import com.samsonmedia.barn.jobs.Job; import com.samsonmedia.barn.jobs.JobRepository; +import com.samsonmedia.barn.jobs.LoadLevel; +import com.samsonmedia.barn.jobs.LoadLevelClassifier; import com.samsonmedia.barn.logging.BarnLogger; import com.samsonmedia.barn.logging.LoggingConfig; import com.samsonmedia.barn.state.BarnDirectories; @@ -48,6 +50,7 @@ public class BarnService { private final JobScheduler scheduler; private final CleanupScheduler cleanupScheduler; private final CrashRecovery crashRecovery; + private final LoadLevelClassifier loadLevelClassifier; private final CountDownLatch shutdownLatch; private final AtomicBoolean running; private final ObjectMapper objectMapper; @@ -71,6 +74,9 @@ public class BarnService { HeartbeatChecker heartbeatChecker = new HeartbeatChecker(heartbeatThreshold); this.crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs, config); + // Load classifier from config directory (if .load files exist) + this.loadLevelClassifier = LoadLevelClassifier.loadFromConfigDir(); + this.shutdownLatch = new CountDownLatch(1); this.running = new AtomicBoolean(false); this.objectMapper = new ObjectMapper(); @@ -316,9 +322,10 @@ public class BarnService { @SuppressWarnings("unchecked") List command = (List) map.get("command"); - String tag = (String) map.get("tag"); - Integer maxRetries = (Integer) map.get("maxRetries"); - Integer retryDelaySeconds = (Integer) map.get("retryDelaySeconds"); + final String tag = (String) map.get("tag"); + final String loadLevelStr = (String) map.get("loadLevel"); + final Integer maxRetries = (Integer) map.get("maxRetries"); + final Integer retryDelaySeconds = (Integer) map.get("retryDelaySeconds"); if (command == null || command.isEmpty()) { throw new IpcException("INVALID_REQUEST", "Command is required"); @@ -335,8 +342,18 @@ public class BarnService { ); } - Job job = repository.create(command, tag, jobsConfig); - LOG.info("Created job via IPC: {}", job.id()); + // Determine load level: use explicit override, or auto-classify + LoadLevel loadLevel; + if (loadLevelStr != null) { + loadLevel = LoadLevel.fromString(loadLevelStr); + LOG.debug("Using explicit load level: {}", loadLevel); + } else { + loadLevel = loadLevelClassifier.classify(command); + LOG.debug("Auto-classified command as load level: {}", loadLevel); + } + + Job job = repository.create(command, tag, jobsConfig, loadLevel); + LOG.info("Created job via IPC: {} (level={})", job.id(), loadLevel); return job; } diff --git a/src/main/resources/META-INF/native-image/com.samsonmedia/barn/resource-config.json b/src/main/resources/META-INF/native-image/com.samsonmedia/barn/resource-config.json index f9603c2..6168189 100644 --- a/src/main/resources/META-INF/native-image/com.samsonmedia/barn/resource-config.json +++ b/src/main/resources/META-INF/native-image/com.samsonmedia/barn/resource-config.json @@ -3,7 +3,8 @@ "includes": [ {"pattern": "logback.xml"}, {"pattern": "version.properties"}, - {"pattern": "META-INF/.*"} + {"pattern": "META-INF/.*"}, + {"pattern": "defaults/.*"} ] }, "bundles": [] diff --git a/src/main/resources/defaults/barn.conf b/src/main/resources/defaults/barn.conf new file mode 100644 index 0000000..24bbc93 --- /dev/null +++ b/src/main/resources/defaults/barn.conf @@ -0,0 +1,67 @@ +# Barn Configuration +# Generated by: barn config install + +[service] +# Logging verbosity: debug, info, warn, error +log_level = "info" + +# DEPRECATED: Use [load_levels] section instead +# max_concurrent_jobs = 4 + +# How often running jobs update their heartbeat (seconds) +heartbeat_interval_seconds = 5 + +# Heartbeat age before a job is considered orphaned (seconds) +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] +# Maximum time a job can run before being killed (seconds) +default_timeout_seconds = 3600 + +# Number of retry attempts for failed jobs +max_retries = 3 + +# Initial delay before first retry (seconds) +retry_delay_seconds = 30 + +# Multiplier applied to delay after each retry +retry_backoff_multiplier = 2.0 + +# Only retry on these exit codes (empty = retry all failures) +retry_on_exit_codes = [] + +[cleanup] +# Enable automatic cleanup of old jobs +enabled = true + +# Remove jobs older than this (hours) +max_age_hours = 72 + +# How often the cleanup task runs (minutes) +cleanup_interval_minutes = 60 + +# Preserve failed jobs for debugging +keep_failed_jobs = true + +# How long to keep failed jobs (hours) +keep_failed_jobs_hours = 168 + +[storage] +# Root directory for all Barn data +base_dir = "/tmp/barn" + +# Maximum disk space Barn can use (GB) +max_disk_usage_gb = 50 + +# Keep work/input and work/output after job completion +preserve_work_dir = false diff --git a/src/main/resources/defaults/high.load b/src/main/resources/defaults/high.load new file mode 100644 index 0000000..462018f --- /dev/null +++ b/src/main/resources/defaults/high.load @@ -0,0 +1,16 @@ +# 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 diff --git a/src/main/resources/defaults/low.load b/src/main/resources/defaults/low.load new file mode 100644 index 0000000..e19e570 --- /dev/null +++ b/src/main/resources/defaults/low.load @@ -0,0 +1,16 @@ +# 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 diff --git a/src/main/resources/defaults/medium.load b/src/main/resources/defaults/medium.load new file mode 100644 index 0000000..b0a7ade --- /dev/null +++ b/src/main/resources/defaults/medium.load @@ -0,0 +1,4 @@ +# Medium load commands +# Maximum concurrent: 8 (default) +# +# Empty by default - unmatched commands are classified as MEDIUM diff --git a/src/test/java/com/samsonmedia/barn/cli/ConfigCommandTest.java b/src/test/java/com/samsonmedia/barn/cli/ConfigCommandTest.java index 0fdbb34..73167f2 100644 --- a/src/test/java/com/samsonmedia/barn/cli/ConfigCommandTest.java +++ b/src/test/java/com/samsonmedia/barn/cli/ConfigCommandTest.java @@ -112,11 +112,12 @@ class ConfigCommandTest { } @Test - void show_withNonExistentConfig_shouldShowDefaultsMessage() { - int exitCode = cmd.execute("config", "show"); + void show_withDefaults_shouldShowDefaultsIndicator() { + // Using --defaults explicitly shows the default values indicator + int exitCode = cmd.execute("config", "show", "--defaults"); assertThat(exitCode).isZero(); - assertThat(outWriter.toString()).contains("(none found, using defaults)"); + assertThat(outWriter.toString()).contains("Showing default values"); } @Test diff --git a/src/test/java/com/samsonmedia/barn/cli/ConfigInstallCommandTest.java b/src/test/java/com/samsonmedia/barn/cli/ConfigInstallCommandTest.java new file mode 100644 index 0000000..fe743b7 --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/cli/ConfigInstallCommandTest.java @@ -0,0 +1,151 @@ +package com.samsonmedia.barn.cli; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.io.PrintWriter; +import java.io.StringWriter; +import java.nio.file.Files; +import java.nio.file.Path; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +import picocli.CommandLine; + +/** + * Tests for ConfigInstallCommand. + */ +class ConfigInstallCommandTest { + + @TempDir + private Path tempDir; + + private StringWriter outWriter; + private StringWriter errWriter; + private CommandLine cmd; + + @BeforeEach + void setUp() { + outWriter = new StringWriter(); + errWriter = new StringWriter(); + cmd = new CommandLine(new BarnCommand()); + cmd.setOut(new PrintWriter(outWriter)); + cmd.setErr(new PrintWriter(errWriter)); + } + + @Nested + class InstallWithForce { + + @Test + void install_withForce_shouldCreateAllFiles() { + Path targetDir = tempDir.resolve("barn-config"); + + int exitCode = cmd.execute("config", "install", + "--directory", targetDir.toString(), + "--force"); + + assertThat(exitCode).isZero(); + assertThat(Files.exists(targetDir.resolve("barn.conf"))).isTrue(); + assertThat(Files.exists(targetDir.resolve("high.load"))).isTrue(); + assertThat(Files.exists(targetDir.resolve("medium.load"))).isTrue(); + assertThat(Files.exists(targetDir.resolve("low.load"))).isTrue(); + } + + @Test + void install_withForce_shouldCreateValidBarnConf() throws Exception { + Path targetDir = tempDir.resolve("barn-config"); + + cmd.execute("config", "install", "--directory", targetDir.toString(), "--force"); + + String content = Files.readString(targetDir.resolve("barn.conf")); + assertThat(content).contains("[service]"); + assertThat(content).contains("[load_levels]"); + assertThat(content).contains("[jobs]"); + assertThat(content).contains("[cleanup]"); + assertThat(content).contains("[storage]"); + } + + @Test + void install_withForce_shouldCreateValidHighLoad() throws Exception { + Path targetDir = tempDir.resolve("barn-config"); + + cmd.execute("config", "install", "--directory", targetDir.toString(), "--force"); + + String content = Files.readString(targetDir.resolve("high.load")); + assertThat(content).contains("ffmpeg"); + assertThat(content).contains("x264"); + } + + @Test + void install_withForce_shouldCreateValidLowLoad() throws Exception { + Path targetDir = tempDir.resolve("barn-config"); + + cmd.execute("config", "install", "--directory", targetDir.toString(), "--force"); + + String content = Files.readString(targetDir.resolve("low.load")); + assertThat(content).contains("curl"); + assertThat(content).contains("wget"); + } + + @Test + void install_withForce_shouldOverwriteExistingFiles() throws Exception { + Path targetDir = tempDir.resolve("barn-config"); + Files.createDirectories(targetDir); + Files.writeString(targetDir.resolve("barn.conf"), "old content"); + + int exitCode = cmd.execute("config", "install", + "--directory", targetDir.toString(), + "--force"); + + assertThat(exitCode).isZero(); + String content = Files.readString(targetDir.resolve("barn.conf")); + assertThat(content).contains("[service]"); + assertThat(content).doesNotContain("old content"); + } + } + + @Nested + class ShowOption { + + @Test + void install_withShow_shouldNotWriteFiles() { + Path targetDir = tempDir.resolve("barn-config"); + + int exitCode = cmd.execute("config", "install", + "--directory", targetDir.toString(), + "--show"); + + assertThat(exitCode).isZero(); + assertThat(Files.exists(targetDir)).isFalse(); + } + + @Test + void install_withShow_shouldDisplayFileList() { + Path targetDir = tempDir.resolve("barn-config"); + + cmd.execute("config", "install", + "--directory", targetDir.toString(), + "--show"); + + String output = outWriter.toString(); + assertThat(output).contains("barn.conf"); + assertThat(output).contains("high.load"); + assertThat(output).contains("medium.load"); + assertThat(output).contains("low.load"); + } + } + + @Nested + class HelpOption { + + @Test + void install_withHelp_shouldShowUsage() { + int exitCode = cmd.execute("config", "install", "--help"); + + assertThat(exitCode).isZero(); + assertThat(outWriter.toString()).contains("Install default configuration files"); + } + } +} diff --git a/src/test/java/com/samsonmedia/barn/cli/HumanFormatterTest.java b/src/test/java/com/samsonmedia/barn/cli/HumanFormatterTest.java index e247b53..41772c7 100644 --- a/src/test/java/com/samsonmedia/barn/cli/HumanFormatterTest.java +++ b/src/test/java/com/samsonmedia/barn/cli/HumanFormatterTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.cli; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; @@ -50,6 +51,8 @@ class HumanFormatterTest { assertThat(result).contains("Job: job-12345678"); assertThat(result).contains("State:"); assertThat(result).contains("running"); + assertThat(result).contains("Load:"); + assertThat(result).contains("medium"); assertThat(result).contains("Tag:"); assertThat(result).contains("test-tag"); } @@ -115,11 +118,13 @@ class HumanFormatterTest { assertThat(result).contains("ID"); assertThat(result).contains("STATE"); + assertThat(result).contains("LOAD"); assertThat(result).contains("TAG"); assertThat(result).contains("job-11111111"); assertThat(result).contains("job-22222222"); assertThat(result).contains("running"); assertThat(result).contains("queued"); + assertThat(result).contains("medium"); } @Test @@ -195,7 +200,8 @@ class HumanFormatterTest { state == JobState.RUNNING ? 12345L : null, null, 0, - null + null, + MEDIUM ); } @@ -213,7 +219,8 @@ class HumanFormatterTest { null, null, 0, - null + null, + MEDIUM ); } @@ -231,7 +238,8 @@ class HumanFormatterTest { null, null, 0, - null + null, + MEDIUM ); } } diff --git a/src/test/java/com/samsonmedia/barn/cli/JsonFormatterTest.java b/src/test/java/com/samsonmedia/barn/cli/JsonFormatterTest.java index 8d9e13b..7d58339 100644 --- a/src/test/java/com/samsonmedia/barn/cli/JsonFormatterTest.java +++ b/src/test/java/com/samsonmedia/barn/cli/JsonFormatterTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.cli; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; @@ -195,7 +196,8 @@ class JsonFormatterTest { state == JobState.RUNNING ? 12345L : null, null, 0, - null + null, + MEDIUM ); } } diff --git a/src/test/java/com/samsonmedia/barn/cli/ServiceInstallCommandTest.java b/src/test/java/com/samsonmedia/barn/cli/ServiceInstallCommandTest.java index 428817f..0210cf9 100644 --- a/src/test/java/com/samsonmedia/barn/cli/ServiceInstallCommandTest.java +++ b/src/test/java/com/samsonmedia/barn/cli/ServiceInstallCommandTest.java @@ -50,7 +50,8 @@ class ServiceInstallCommandTest { int exitCode = cmd.execute("service", "install", "--help"); assertThat(exitCode).isEqualTo(0); assertThat(stdout.toString()).contains("Install Barn as a system service"); - assertThat(stdout.toString()).contains("--user"); + assertThat(stdout.toString()).contains("--binary"); + assertThat(stdout.toString()).contains("--barn-dir"); } @Test @@ -81,7 +82,6 @@ class ServiceInstallCommandTest { int exitCode = cmd.execute("service", "uninstall", "--help"); assertThat(exitCode).isEqualTo(0); assertThat(stdout.toString()).contains("Uninstall Barn system service"); - assertThat(stdout.toString()).contains("--user"); assertThat(stdout.toString()).contains("--force"); } } diff --git a/src/test/java/com/samsonmedia/barn/cli/XmlFormatterTest.java b/src/test/java/com/samsonmedia/barn/cli/XmlFormatterTest.java index 6c58f04..18cf3cb 100644 --- a/src/test/java/com/samsonmedia/barn/cli/XmlFormatterTest.java +++ b/src/test/java/com/samsonmedia/barn/cli/XmlFormatterTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.cli; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThat; import java.time.Duration; @@ -207,7 +208,8 @@ class XmlFormatterTest { state == JobState.RUNNING ? 12345L : null, null, 0, - null + null, + MEDIUM ); } } diff --git a/src/test/java/com/samsonmedia/barn/config/CommandMatcherTest.java b/src/test/java/com/samsonmedia/barn/config/CommandMatcherTest.java new file mode 100644 index 0000000..556bea7 --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/config/CommandMatcherTest.java @@ -0,0 +1,140 @@ +package com.samsonmedia.barn.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.nio.file.Path; +import java.util.List; + +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; + +/** + * Tests for CommandMatcher sealed interface and implementations. + */ +class CommandMatcherTest { + + @Nested + class ExecutableNameMatcherTests { + + @Test + void matches_withMatchingExecutableName_shouldReturnTrue() { + var matcher = new CommandMatcher.ExecutableName("ffmpeg"); + + assertThat(matcher.matches(List.of("ffmpeg", "-i", "input.mp4"))).isTrue(); + assertThat(matcher.matches(List.of("/usr/bin/ffmpeg", "-i", "input.mp4"))).isTrue(); + assertThat(matcher.matches(List.of("/opt/local/bin/ffmpeg", "-version"))).isTrue(); + } + + @Test + void matches_withNonMatchingExecutableName_shouldReturnFalse() { + var matcher = new CommandMatcher.ExecutableName("ffmpeg"); + + assertThat(matcher.matches(List.of("curl", "http://example.com"))).isFalse(); + assertThat(matcher.matches(List.of("/usr/bin/curl", "-O", "file"))).isFalse(); + } + + @Test + void matches_withPartialMatch_shouldReturnFalse() { + var matcher = new CommandMatcher.ExecutableName("ffmpeg"); + + // ffmpegXXX should not match + assertThat(matcher.matches(List.of("ffmpegXXX", "-i", "input.mp4"))).isFalse(); + // prefix should not match + assertThat(matcher.matches(List.of("/usr/bin/ffmpegXXX", "-version"))).isFalse(); + } + + @Test + void matches_withEmptyCommand_shouldReturnFalse() { + var matcher = new CommandMatcher.ExecutableName("ffmpeg"); + + assertThat(matcher.matches(List.of())).isFalse(); + } + + @Test + void constructor_withNull_shouldThrowException() { + assertThatThrownBy(() -> new CommandMatcher.ExecutableName(null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + void constructor_withBlank_shouldThrowException() { + assertThatThrownBy(() -> new CommandMatcher.ExecutableName(" ")) + .isInstanceOf(IllegalArgumentException.class); + } + } + + @Nested + class FullPathMatcherTests { + + @Test + void matches_withExactPath_shouldReturnTrue() { + var matcher = new CommandMatcher.FullPath(Path.of("/usr/local/bin/ffmpeg")); + + assertThat(matcher.matches(List.of("/usr/local/bin/ffmpeg", "-i", "input.mp4"))).isTrue(); + } + + @Test + void matches_withDifferentPath_shouldReturnFalse() { + var matcher = new CommandMatcher.FullPath(Path.of("/usr/local/bin/ffmpeg")); + + assertThat(matcher.matches(List.of("/usr/bin/ffmpeg", "-i", "input.mp4"))).isFalse(); + assertThat(matcher.matches(List.of("ffmpeg", "-i", "input.mp4"))).isFalse(); + } + + @Test + void matches_withEmptyCommand_shouldReturnFalse() { + var matcher = new CommandMatcher.FullPath(Path.of("/usr/local/bin/ffmpeg")); + + assertThat(matcher.matches(List.of())).isFalse(); + } + + @Test + void constructor_withNull_shouldThrowException() { + assertThatThrownBy(() -> new CommandMatcher.FullPath(null)) + .isInstanceOf(NullPointerException.class); + } + } + + @Nested + class DirectoryMatcherTests { + + @Test + void matches_withCommandInDirectory_shouldReturnTrue() { + var matcher = new CommandMatcher.Directory(Path.of("/opt/encoders/")); + + assertThat(matcher.matches(List.of("/opt/encoders/x264", "-i", "input.mp4"))).isTrue(); + assertThat(matcher.matches(List.of("/opt/encoders/x265", "-o", "output.mp4"))).isTrue(); + assertThat(matcher.matches(List.of("/opt/encoders/av1an", "-i", "input.mp4"))).isTrue(); + } + + @Test + void matches_withCommandNotInDirectory_shouldReturnFalse() { + var matcher = new CommandMatcher.Directory(Path.of("/opt/encoders/")); + + assertThat(matcher.matches(List.of("/usr/bin/ffmpeg", "-i", "input.mp4"))).isFalse(); + assertThat(matcher.matches(List.of("ffmpeg", "-i", "input.mp4"))).isFalse(); + } + + @Test + void matches_withSubdirectory_shouldReturnFalse() { + var matcher = new CommandMatcher.Directory(Path.of("/opt/encoders/")); + + // Subdirectories should not match + assertThat(matcher.matches(List.of("/opt/encoders/subdir/ffmpeg", "-version"))).isFalse(); + } + + @Test + void matches_withEmptyCommand_shouldReturnFalse() { + var matcher = new CommandMatcher.Directory(Path.of("/opt/encoders/")); + + assertThat(matcher.matches(List.of())).isFalse(); + } + + @Test + void constructor_withNull_shouldThrowException() { + assertThatThrownBy(() -> new CommandMatcher.Directory(null)) + .isInstanceOf(NullPointerException.class); + } + } +} diff --git a/src/test/java/com/samsonmedia/barn/config/ConfigLoaderTest.java b/src/test/java/com/samsonmedia/barn/config/ConfigLoaderTest.java index a5b253f..f6879c2 100644 --- a/src/test/java/com/samsonmedia/barn/config/ConfigLoaderTest.java +++ b/src/test/java/com/samsonmedia/barn/config/ConfigLoaderTest.java @@ -287,6 +287,51 @@ class ConfigLoaderTest { } } + @Nested + class LoadLevelsConfig { + + @Test + void load_withLoadLevels_shouldParseValues() throws IOException { + Path configFile = tempDir.resolve("barn.conf"); + Files.writeString(configFile, """ + [load_levels] + max_high_jobs = 4 + max_medium_jobs = 16 + max_low_jobs = 64 + """); + + ConfigLoader loader = new ConfigLoader(Map.of()); + Config config = loader.loadFromFile(configFile); + + assertThat(config.loadLevels().maxHighJobs()).isEqualTo(4); + assertThat(config.loadLevels().maxMediumJobs()).isEqualTo(16); + assertThat(config.loadLevels().maxLowJobs()).isEqualTo(64); + } + + @Test + void load_withNoLoadLevels_shouldUseDefaults() { + ConfigLoader loader = new ConfigLoader(Map.of()); + Config config = loader.load(); + + assertThat(config.loadLevels().maxHighJobs()).isEqualTo(2); + assertThat(config.loadLevels().maxMediumJobs()).isEqualTo(8); + assertThat(config.loadLevels().maxLowJobs()).isEqualTo(32); + } + + @Test + void load_withEnvOverride_shouldOverrideLoadLevelValues() { + // Environment variables use BARN_LOADLEVELS_ (no underscore) because + // the parser splits on first underscore for section name + Map env = new HashMap<>(); + env.put("BARN_LOADLEVELS_MAX_HIGH_JOBS", "10"); + + ConfigLoader loader = new ConfigLoader(env); + Config config = loader.load(); + + assertThat(config.loadLevels().maxHighJobs()).isEqualTo(10); + } + } + @Nested class RetryOnExitCodes { diff --git a/src/test/java/com/samsonmedia/barn/config/ConfigTest.java b/src/test/java/com/samsonmedia/barn/config/ConfigTest.java index ffdb962..d444c60 100644 --- a/src/test/java/com/samsonmedia/barn/config/ConfigTest.java +++ b/src/test/java/com/samsonmedia/barn/config/ConfigTest.java @@ -222,13 +222,15 @@ class ConfigTest { ServiceConfig.withDefaults(), JobsConfig.withDefaults(), CleanupConfig.withDefaults(), - StorageConfig.withDefaults() + StorageConfig.withDefaults(), + LoadLevelConfig.withDefaults() ); assertThat(config.service()).isNotNull(); assertThat(config.jobs()).isNotNull(); assertThat(config.cleanup()).isNotNull(); assertThat(config.storage()).isNotNull(); + assertThat(config.loadLevels()).isNotNull(); } @Test @@ -237,7 +239,8 @@ class ConfigTest { null, JobsConfig.withDefaults(), CleanupConfig.withDefaults(), - StorageConfig.withDefaults())) + StorageConfig.withDefaults(), + LoadLevelConfig.withDefaults())) .isInstanceOf(NullPointerException.class) .hasMessageContaining("service"); } @@ -248,11 +251,24 @@ class ConfigTest { ServiceConfig.withDefaults(), null, CleanupConfig.withDefaults(), - StorageConfig.withDefaults())) + StorageConfig.withDefaults(), + LoadLevelConfig.withDefaults())) .isInstanceOf(NullPointerException.class) .hasMessageContaining("jobs"); } + @Test + void constructor_withNullLoadLevels_shouldThrowException() { + assertThatThrownBy(() -> new Config( + ServiceConfig.withDefaults(), + JobsConfig.withDefaults(), + CleanupConfig.withDefaults(), + StorageConfig.withDefaults(), + null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("loadLevels"); + } + @Test void withDefaults_shouldReturnFullyPopulatedConfig() { Config config = Config.withDefaults(); @@ -261,6 +277,7 @@ class ConfigTest { assertThat(config.jobs()).isNotNull(); assertThat(config.cleanup()).isNotNull(); assertThat(config.storage()).isNotNull(); + assertThat(config.loadLevels()).isNotNull(); } } } diff --git a/src/test/java/com/samsonmedia/barn/config/LoadFileParserTest.java b/src/test/java/com/samsonmedia/barn/config/LoadFileParserTest.java new file mode 100644 index 0000000..747ca94 --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/config/LoadFileParserTest.java @@ -0,0 +1,175 @@ +package com.samsonmedia.barn.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Tests for LoadFileParser. + */ +class LoadFileParserTest { + + @TempDir + private Path tempDir; + + @Test + void parse_withEmptyFile_shouldReturnEmptyList() throws IOException { + Path loadFile = tempDir.resolve("empty.load"); + Files.writeString(loadFile, ""); + + List matchers = LoadFileParser.parse(loadFile); + + assertThat(matchers).isEmpty(); + } + + @Test + void parse_withOnlyComments_shouldReturnEmptyList() throws IOException { + Path loadFile = tempDir.resolve("comments.load"); + Files.writeString(loadFile, """ + # This is a comment + # Another comment + """); + + List matchers = LoadFileParser.parse(loadFile); + + assertThat(matchers).isEmpty(); + } + + @Test + void parse_withOnlyBlankLines_shouldReturnEmptyList() throws IOException { + Path loadFile = tempDir.resolve("blank.load"); + Files.writeString(loadFile, """ + + \s\s + \t + """); + + List matchers = LoadFileParser.parse(loadFile); + + assertThat(matchers).isEmpty(); + } + + @Test + void parse_withExecutableNames_shouldReturnExecutableNameMatchers() throws IOException { + Path loadFile = tempDir.resolve("executables.load"); + Files.writeString(loadFile, """ + ffmpeg + ffprobe + handbrake + """); + + List matchers = LoadFileParser.parse(loadFile); + + assertThat(matchers).hasSize(3); + assertThat(matchers.get(0)).isInstanceOf(CommandMatcher.ExecutableName.class); + assertThat(matchers.get(1)).isInstanceOf(CommandMatcher.ExecutableName.class); + assertThat(matchers.get(2)).isInstanceOf(CommandMatcher.ExecutableName.class); + } + + @Test + void parse_withFullPaths_shouldReturnFullPathMatchers() throws IOException { + Path loadFile = tempDir.resolve("paths.load"); + Files.writeString(loadFile, """ + /usr/local/bin/ffmpeg + /opt/media/encoders/x264 + """); + + List matchers = LoadFileParser.parse(loadFile); + + assertThat(matchers).hasSize(2); + assertThat(matchers.get(0)).isInstanceOf(CommandMatcher.FullPath.class); + assertThat(matchers.get(1)).isInstanceOf(CommandMatcher.FullPath.class); + } + + @Test + void parse_withDirectoryPaths_shouldReturnDirectoryMatchers() throws IOException { + Path loadFile = tempDir.resolve("dirs.load"); + Files.writeString(loadFile, """ + /opt/encoders/ + /usr/local/media/ + """); + + List matchers = LoadFileParser.parse(loadFile); + + assertThat(matchers).hasSize(2); + assertThat(matchers.get(0)).isInstanceOf(CommandMatcher.Directory.class); + assertThat(matchers.get(1)).isInstanceOf(CommandMatcher.Directory.class); + } + + @Test + void parse_withMixedEntries_shouldReturnCorrectMatchers() throws IOException { + Path loadFile = tempDir.resolve("mixed.load"); + Files.writeString(loadFile, """ + # High load commands + ffmpeg + /usr/local/bin/custom-encoder + /opt/encoders/ + + # More commands + handbrake + """); + + List matchers = LoadFileParser.parse(loadFile); + + assertThat(matchers).hasSize(4); + assertThat(matchers.get(0)).isInstanceOf(CommandMatcher.ExecutableName.class); + assertThat(matchers.get(1)).isInstanceOf(CommandMatcher.FullPath.class); + assertThat(matchers.get(2)).isInstanceOf(CommandMatcher.Directory.class); + assertThat(matchers.get(3)).isInstanceOf(CommandMatcher.ExecutableName.class); + } + + @Test + void parse_withNonExistentFile_shouldThrowIOException() { + Path nonExistent = tempDir.resolve("nonexistent.load"); + + assertThatThrownBy(() -> LoadFileParser.parse(nonExistent)) + .isInstanceOf(IOException.class); + } + + @Test + void parse_withNullPath_shouldThrowException() { + assertThatThrownBy(() -> LoadFileParser.parse(null)) + .isInstanceOf(NullPointerException.class); + } + + @Test + void parse_withWhitespaceAroundEntries_shouldTrimEntries() throws IOException { + Path loadFile = tempDir.resolve("whitespace.load"); + Files.writeString(loadFile, """ + ffmpeg \s + \t curl\t + """); + + List matchers = LoadFileParser.parse(loadFile); + + assertThat(matchers).hasSize(2); + assertThat(matchers.get(0).matches(List.of("ffmpeg", "-version"))).isTrue(); + assertThat(matchers.get(1).matches(List.of("curl", "--help"))).isTrue(); + } + + @Test + void parseIfExists_withExistingFile_shouldReturnMatchers() throws IOException { + Path loadFile = tempDir.resolve("existing.load"); + Files.writeString(loadFile, "ffmpeg\n"); + + List matchers = LoadFileParser.parseIfExists(loadFile); + + assertThat(matchers).hasSize(1); + } + + @Test + void parseIfExists_withNonExistentFile_shouldReturnEmptyList() { + Path nonExistent = tempDir.resolve("nonexistent.load"); + + List matchers = LoadFileParser.parseIfExists(nonExistent); + + assertThat(matchers).isEmpty(); + } +} diff --git a/src/test/java/com/samsonmedia/barn/config/LoadLevelConfigTest.java b/src/test/java/com/samsonmedia/barn/config/LoadLevelConfigTest.java new file mode 100644 index 0000000..a3d99d3 --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/config/LoadLevelConfigTest.java @@ -0,0 +1,92 @@ +package com.samsonmedia.barn.config; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +import com.samsonmedia.barn.jobs.LoadLevel; + +/** + * Tests for LoadLevelConfig record. + */ +class LoadLevelConfigTest { + + @Test + void constructor_withValidValues_shouldCreateConfig() { + var config = new LoadLevelConfig(4, 16, 64); + + assertThat(config.maxHighJobs()).isEqualTo(4); + assertThat(config.maxMediumJobs()).isEqualTo(16); + assertThat(config.maxLowJobs()).isEqualTo(64); + } + + @Test + void constructor_withZeroHighJobs_shouldThrowException() { + assertThatThrownBy(() -> new LoadLevelConfig(0, 8, 32)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("maxHighJobs must be at least 1"); + } + + @Test + void constructor_withNegativeHighJobs_shouldThrowException() { + assertThatThrownBy(() -> new LoadLevelConfig(-1, 8, 32)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("maxHighJobs must be at least 1"); + } + + @Test + void constructor_withZeroMediumJobs_shouldThrowException() { + assertThatThrownBy(() -> new LoadLevelConfig(2, 0, 32)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("maxMediumJobs must be at least 1"); + } + + @Test + void constructor_withZeroLowJobs_shouldThrowException() { + assertThatThrownBy(() -> new LoadLevelConfig(2, 8, 0)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("maxLowJobs must be at least 1"); + } + + @Test + void withDefaults_shouldReturnDefaultValues() { + var config = LoadLevelConfig.withDefaults(); + + assertThat(config.maxHighJobs()).isEqualTo(LoadLevelConfig.DEFAULT_MAX_HIGH_JOBS); + assertThat(config.maxMediumJobs()).isEqualTo(LoadLevelConfig.DEFAULT_MAX_MEDIUM_JOBS); + assertThat(config.maxLowJobs()).isEqualTo(LoadLevelConfig.DEFAULT_MAX_LOW_JOBS); + } + + @Test + void defaultConstants_shouldMatchLoadLevelDefaults() { + assertThat(LoadLevelConfig.DEFAULT_MAX_HIGH_JOBS).isEqualTo(LoadLevel.HIGH.getDefaultMaxJobs()); + assertThat(LoadLevelConfig.DEFAULT_MAX_MEDIUM_JOBS).isEqualTo(LoadLevel.MEDIUM.getDefaultMaxJobs()); + assertThat(LoadLevelConfig.DEFAULT_MAX_LOW_JOBS).isEqualTo(LoadLevel.LOW.getDefaultMaxJobs()); + } + + @Test + void getMaxJobsFor_shouldReturnCorrectLimit() { + var config = new LoadLevelConfig(4, 16, 64); + + assertThat(config.getMaxJobsFor(LoadLevel.HIGH)).isEqualTo(4); + assertThat(config.getMaxJobsFor(LoadLevel.MEDIUM)).isEqualTo(16); + assertThat(config.getMaxJobsFor(LoadLevel.LOW)).isEqualTo(64); + } + + @Test + void getMaxJobsFor_withNull_shouldThrowException() { + var config = LoadLevelConfig.withDefaults(); + + assertThatThrownBy(() -> config.getMaxJobsFor(null)) + .isInstanceOf(NullPointerException.class) + .hasMessageContaining("level must not be null"); + } + + @Test + void getTotalMaxJobs_shouldReturnSum() { + var config = new LoadLevelConfig(4, 16, 64); + + assertThat(config.getTotalMaxJobs()).isEqualTo(84); + } +} diff --git a/src/test/java/com/samsonmedia/barn/execution/CrashRecoveryTest.java b/src/test/java/com/samsonmedia/barn/execution/CrashRecoveryTest.java index 807c8a1..ce682bd 100644 --- a/src/test/java/com/samsonmedia/barn/execution/CrashRecoveryTest.java +++ b/src/test/java/com/samsonmedia/barn/execution/CrashRecoveryTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.execution; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -212,7 +213,8 @@ class CrashRecoveryTest { config.service(), new JobsConfig(config.jobs().defaultTimeoutSeconds(), 0, 1, 1.0, List.of()), config.cleanup(), - config.storage() + config.storage(), + config.loadLevels() ); CrashRecovery noRetryCrashRecovery = new CrashRecovery( repository, heartbeatChecker, dirs, noRetryConfig); @@ -296,7 +298,8 @@ class CrashRecoveryTest { pid, heartbeat, 0, // retryCount - null // retryAt + null, // retryAt + MEDIUM ); } } diff --git a/src/test/java/com/samsonmedia/barn/execution/HeartbeatCheckerTest.java b/src/test/java/com/samsonmedia/barn/execution/HeartbeatCheckerTest.java index a44139f..5435df8 100644 --- a/src/test/java/com/samsonmedia/barn/execution/HeartbeatCheckerTest.java +++ b/src/test/java/com/samsonmedia/barn/execution/HeartbeatCheckerTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.execution; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -161,7 +162,8 @@ class HeartbeatCheckerTest { state == JobState.RUNNING ? 12345L : null, // pid heartbeat, 0, // retryCount - null // retryAt + null, // retryAt + MEDIUM ); } } diff --git a/src/test/java/com/samsonmedia/barn/execution/JobSchedulerTest.java b/src/test/java/com/samsonmedia/barn/execution/JobSchedulerTest.java index 7314c17..70bb471 100644 --- a/src/test/java/com/samsonmedia/barn/execution/JobSchedulerTest.java +++ b/src/test/java/com/samsonmedia/barn/execution/JobSchedulerTest.java @@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import com.samsonmedia.barn.config.JobsConfig; +import com.samsonmedia.barn.config.LoadLevelConfig; import com.samsonmedia.barn.jobs.Job; import com.samsonmedia.barn.jobs.JobRepository; import com.samsonmedia.barn.state.BarnDirectories; @@ -189,13 +190,15 @@ class JobSchedulerTest { @Test void getStatus_whenNotRunning_shouldShowNotRunning() { + // Legacy constructor with maxConcurrentJobs=2 creates config with 1 HIGH + 2 MEDIUM + 1 LOW = 4 total scheduler = new JobScheduler(repository, runner, dirs, 2, Duration.ofMillis(100), Duration.ofSeconds(5)); JobScheduler.SchedulerStatus status = scheduler.getStatus(); assertThat(status.isRunning()).isFalse(); - assertThat(status.maxConcurrentJobs()).isEqualTo(2); + assertThat(status.maxConcurrentJobs()).isEqualTo(4); // 1 + 2 + 1 + assertThat(status.maxMediumJobs()).isEqualTo(2); // The configured value } @Test @@ -279,6 +282,56 @@ class JobSchedulerTest { assertThat(status.maxConcurrentJobs()).isEqualTo(8); assertThat(status.isRunning()).isTrue(); } + + @Test + void schedulerStatus_withPerLevelFields_shouldContainAllFields() { + JobScheduler.SchedulerStatus status = new JobScheduler.SchedulerStatus( + 10, 5, 42, true, 2, 5, 3, 4, 8, 30); + + assertThat(status.runningJobs()).isEqualTo(10); + assertThat(status.queuedJobs()).isEqualTo(5); + assertThat(status.maxConcurrentJobs()).isEqualTo(42); + assertThat(status.isRunning()).isTrue(); + assertThat(status.runningHighJobs()).isEqualTo(2); + assertThat(status.runningMediumJobs()).isEqualTo(5); + assertThat(status.runningLowJobs()).isEqualTo(3); + assertThat(status.maxHighJobs()).isEqualTo(4); + assertThat(status.maxMediumJobs()).isEqualTo(8); + assertThat(status.maxLowJobs()).isEqualTo(30); + } + } + + @Nested + class PerLevelScheduling { + + @Test + void constructor_withLoadLevelConfig_shouldUsePerLevelLimits() throws IOException { + LoadLevelConfig levelConfig = new LoadLevelConfig(2, 4, 8); + scheduler = new JobScheduler(repository, runner, dirs, levelConfig, + Duration.ofMillis(100), Duration.ofSeconds(5)); + + JobScheduler.SchedulerStatus status = scheduler.getStatus(); + + assertThat(status.maxHighJobs()).isEqualTo(2); + assertThat(status.maxMediumJobs()).isEqualTo(4); + assertThat(status.maxLowJobs()).isEqualTo(8); + assertThat(status.maxConcurrentJobs()).isEqualTo(14); // 2 + 4 + 8 + } + + @Test + void getStatus_shouldReportPerLevelRunningCounts() throws IOException { + LoadLevelConfig levelConfig = new LoadLevelConfig(2, 4, 8); + scheduler = new JobScheduler(repository, runner, dirs, levelConfig, + Duration.ofMillis(100), Duration.ofSeconds(5)); + + JobScheduler.SchedulerStatus status = scheduler.getStatus(); + + // Initially no jobs are running + assertThat(status.runningHighJobs()).isZero(); + assertThat(status.runningMediumJobs()).isZero(); + assertThat(status.runningLowJobs()).isZero(); + assertThat(status.runningJobs()).isZero(); + } } // Helper methods diff --git a/src/test/java/com/samsonmedia/barn/jobs/JobManifestTest.java b/src/test/java/com/samsonmedia/barn/jobs/JobManifestTest.java index 531ad48..02f787b 100644 --- a/src/test/java/com/samsonmedia/barn/jobs/JobManifestTest.java +++ b/src/test/java/com/samsonmedia/barn/jobs/JobManifestTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.jobs; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -23,7 +24,7 @@ class JobManifestTest { List.of("echo", "hello"), "test-tag", now, - 3, 30, 2.0 + 3, 30, 2.0, MEDIUM ); assertThat(manifest.id()).isEqualTo("job-12345"); @@ -38,7 +39,7 @@ class JobManifestTest { @Test void constructor_withNullId_shouldThrowException() { assertThatThrownBy(() -> new JobManifest( - null, List.of("echo"), null, Instant.now(), 3, 30, 2.0)) + null, List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("id"); } @@ -46,7 +47,7 @@ class JobManifestTest { @Test void constructor_withBlankId_shouldThrowException() { assertThatThrownBy(() -> new JobManifest( - " ", List.of("echo"), null, Instant.now(), 3, 30, 2.0)) + " ", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("blank"); } @@ -54,7 +55,7 @@ class JobManifestTest { @Test void constructor_withEmptyCommand_shouldThrowException() { assertThatThrownBy(() -> new JobManifest( - "job-12345", List.of(), null, Instant.now(), 3, 30, 2.0)) + "job-12345", List.of(), null, Instant.now(), 3, 30, 2.0, MEDIUM)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("empty"); } @@ -62,7 +63,7 @@ class JobManifestTest { @Test void constructor_withNegativeMaxRetries_shouldThrowException() { assertThatThrownBy(() -> new JobManifest( - "job-12345", List.of("echo"), null, Instant.now(), -1, 30, 2.0)) + "job-12345", List.of("echo"), null, Instant.now(), -1, 30, 2.0, MEDIUM)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("maxRetries"); } @@ -70,7 +71,7 @@ class JobManifestTest { @Test void constructor_withNegativeRetryDelay_shouldThrowException() { assertThatThrownBy(() -> new JobManifest( - "job-12345", List.of("echo"), null, Instant.now(), 3, -1, 2.0)) + "job-12345", List.of("echo"), null, Instant.now(), 3, -1, 2.0, MEDIUM)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("retryDelaySeconds"); } @@ -78,7 +79,7 @@ class JobManifestTest { @Test void constructor_withBackoffMultiplierLessThanOne_shouldThrowException() { assertThatThrownBy(() -> new JobManifest( - "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 0.5)) + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 0.5, MEDIUM)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("retryBackoffMultiplier"); } @@ -107,7 +108,7 @@ class JobManifestTest { @Test void calculateRetryDelay_shouldUseExponentialBackoff() { JobManifest manifest = new JobManifest( - "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0); + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM); assertThat(manifest.calculateRetryDelay(0)).isEqualTo(30); // 30 * 2^0 assertThat(manifest.calculateRetryDelay(1)).isEqualTo(60); // 30 * 2^1 @@ -117,7 +118,7 @@ class JobManifestTest { @Test void calculateRetryDelay_withNegativeCount_shouldThrowException() { JobManifest manifest = new JobManifest( - "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0); + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM); assertThatThrownBy(() -> manifest.calculateRetryDelay(-1)) .isInstanceOf(IllegalArgumentException.class); @@ -126,7 +127,7 @@ class JobManifestTest { @Test void canRetry_withRetriesAvailable_shouldReturnTrue() { JobManifest manifest = new JobManifest( - "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0); + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM); assertThat(manifest.canRetry(0)).isTrue(); assertThat(manifest.canRetry(1)).isTrue(); @@ -136,7 +137,7 @@ class JobManifestTest { @Test void canRetry_withNoRetriesLeft_shouldReturnFalse() { JobManifest manifest = new JobManifest( - "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0); + "job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM); assertThat(manifest.canRetry(3)).isFalse(); assertThat(manifest.canRetry(4)).isFalse(); @@ -145,7 +146,7 @@ class JobManifestTest { @Test void canRetry_withZeroMaxRetries_shouldAlwaysReturnFalse() { JobManifest manifest = new JobManifest( - "job-12345", List.of("echo"), null, Instant.now(), 0, 30, 2.0); + "job-12345", List.of("echo"), null, Instant.now(), 0, 30, 2.0, MEDIUM); assertThat(manifest.canRetry(0)).isFalse(); } diff --git a/src/test/java/com/samsonmedia/barn/jobs/JobRepositoryTest.java b/src/test/java/com/samsonmedia/barn/jobs/JobRepositoryTest.java index 2ad63e7..7d49d36 100644 --- a/src/test/java/com/samsonmedia/barn/jobs/JobRepositoryTest.java +++ b/src/test/java/com/samsonmedia/barn/jobs/JobRepositoryTest.java @@ -83,6 +83,39 @@ class JobRepositoryTest { assertThat(job.tag()).isNull(); } + + @Test + void create_shouldDefaultToMediumLoadLevel() throws IOException { + Job job = repository.create(List.of("echo"), null, config); + + assertThat(job.loadLevel()).isEqualTo(LoadLevel.MEDIUM); + } + + @Test + void create_withLoadLevel_shouldUseSpecifiedLevel() throws IOException { + Job job = repository.create(List.of("ffmpeg", "-version"), null, config, LoadLevel.HIGH); + + assertThat(job.loadLevel()).isEqualTo(LoadLevel.HIGH); + } + + @Test + void create_withLoadLevel_shouldPersistInManifest() throws IOException { + Job job = repository.create(List.of("curl", "-h"), null, config, LoadLevel.LOW); + + Path manifestPath = dirs.getJobDir(job.id()).resolve("manifest.json"); + String content = Files.readString(manifestPath); + assertThat(content).contains("\"loadLevel\" : \"LOW\""); + } + + @Test + void create_withLoadLevel_shouldBeReadableByFindById() throws IOException { + Job created = repository.create(List.of("wget"), null, config, LoadLevel.LOW); + + Optional found = repository.findById(created.id()); + + assertThat(found).isPresent(); + assertThat(found.get().loadLevel()).isEqualTo(LoadLevel.LOW); + } } @Nested diff --git a/src/test/java/com/samsonmedia/barn/jobs/JobTest.java b/src/test/java/com/samsonmedia/barn/jobs/JobTest.java index d36af99..16eb02c 100644 --- a/src/test/java/com/samsonmedia/barn/jobs/JobTest.java +++ b/src/test/java/com/samsonmedia/barn/jobs/JobTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.jobs; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -23,7 +24,7 @@ class JobTest { List.of("echo", "hello"), "test-tag", Instant.now(), - null, null, null, null, null, null, 0, null + null, null, null, null, null, null, 0, null, MEDIUM ); assertThat(job.id()).isEqualTo("job-12345"); @@ -36,7 +37,7 @@ class JobTest { void constructor_withNullId_shouldThrowException() { assertThatThrownBy(() -> new Job( null, JobState.QUEUED, List.of("echo"), null, - Instant.now(), null, null, null, null, null, null, 0, null)) + Instant.now(), null, null, null, null, null, null, 0, null, MEDIUM)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("id"); } @@ -45,7 +46,7 @@ class JobTest { void constructor_withBlankId_shouldThrowException() { assertThatThrownBy(() -> new Job( " ", JobState.QUEUED, List.of("echo"), null, - Instant.now(), null, null, null, null, null, null, 0, null)) + Instant.now(), null, null, null, null, null, null, 0, null, MEDIUM)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("blank"); } @@ -54,7 +55,7 @@ class JobTest { void constructor_withNullState_shouldThrowException() { assertThatThrownBy(() -> new Job( "job-12345", null, List.of("echo"), null, - Instant.now(), null, null, null, null, null, null, 0, null)) + Instant.now(), null, null, null, null, null, null, 0, null, MEDIUM)) .isInstanceOf(NullPointerException.class) .hasMessageContaining("state"); } @@ -63,7 +64,7 @@ class JobTest { void constructor_withEmptyCommand_shouldThrowException() { assertThatThrownBy(() -> new Job( "job-12345", JobState.QUEUED, List.of(), null, - Instant.now(), null, null, null, null, null, null, 0, null)) + Instant.now(), null, null, null, null, null, null, 0, null, MEDIUM)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("empty"); } @@ -72,7 +73,7 @@ class JobTest { void constructor_withNegativeRetryCount_shouldThrowException() { assertThatThrownBy(() -> new Job( "job-12345", JobState.QUEUED, List.of("echo"), null, - Instant.now(), null, null, null, null, null, null, -1, null)) + Instant.now(), null, null, null, null, null, null, -1, null, MEDIUM)) .isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("retryCount"); } @@ -231,4 +232,29 @@ class JobTest { assertThat(queued.isQueued()).isTrue(); assertThat(running.isQueued()).isFalse(); } + + @Test + void createQueued_shouldDefaultToMediumLoadLevel() { + Job job = Job.createQueued("job-12345", List.of("echo", "test"), "my-tag"); + + assertThat(job.loadLevel()).isEqualTo(LoadLevel.MEDIUM); + } + + @Test + void createQueued_withLoadLevel_shouldUseSpecifiedLevel() { + Job job = Job.createQueued("job-12345", List.of("ffmpeg", "-i", "input.mp4"), + "transcode", LoadLevel.HIGH); + + assertThat(job.loadLevel()).isEqualTo(LoadLevel.HIGH); + } + + @Test + void withLoadLevel_shouldCreateCopyWithNewLoadLevel() { + Job original = Job.createQueued("job-12345", List.of("echo"), null); + + Job updated = original.withLoadLevel(LoadLevel.LOW); + + assertThat(updated.loadLevel()).isEqualTo(LoadLevel.LOW); + assertThat(original.loadLevel()).isEqualTo(LoadLevel.MEDIUM); // Original unchanged + } } diff --git a/src/test/java/com/samsonmedia/barn/jobs/LoadLevelClassifierTest.java b/src/test/java/com/samsonmedia/barn/jobs/LoadLevelClassifierTest.java new file mode 100644 index 0000000..4eddb7a --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/jobs/LoadLevelClassifierTest.java @@ -0,0 +1,149 @@ +package com.samsonmedia.barn.jobs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Nested; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; + +/** + * Tests for LoadLevelClassifier. + */ +class LoadLevelClassifierTest { + + @TempDir + private Path tempDir; + + @Nested + class ClassificationTests { + + private LoadLevelClassifier classifier; + + @BeforeEach + void setUp() throws IOException { + // Create high.load with ffmpeg, x264 + Files.writeString(tempDir.resolve("high.load"), """ + # High load commands + ffmpeg + x264 + /usr/local/bin/handbrake + """); + + // Create empty medium.load + Files.writeString(tempDir.resolve("medium.load"), """ + # Medium load - empty by default + """); + + // Create low.load with curl, wget + Files.writeString(tempDir.resolve("low.load"), """ + # Low load commands + curl + wget + rclone + """); + + classifier = LoadLevelClassifier.load(tempDir); + } + + @Test + void classify_withHighLoadCommand_shouldReturnHigh() { + assertThat(classifier.classify(List.of("ffmpeg", "-i", "input.mp4"))).isEqualTo(LoadLevel.HIGH); + assertThat(classifier.classify(List.of("/usr/bin/ffmpeg", "-version"))).isEqualTo(LoadLevel.HIGH); + assertThat(classifier.classify(List.of("x264", "--preset", "slow"))).isEqualTo(LoadLevel.HIGH); + assertThat(classifier.classify(List.of("/usr/local/bin/handbrake", "-i", "input"))).isEqualTo(LoadLevel.HIGH); + } + + @Test + void classify_withLowLoadCommand_shouldReturnLow() { + assertThat(classifier.classify(List.of("curl", "http://example.com"))).isEqualTo(LoadLevel.LOW); + assertThat(classifier.classify(List.of("/usr/bin/wget", "-O", "file"))).isEqualTo(LoadLevel.LOW); + assertThat(classifier.classify(List.of("rclone", "sync", "source:", "dest:"))).isEqualTo(LoadLevel.LOW); + } + + @Test + void classify_withUnknownCommand_shouldReturnMedium() { + assertThat(classifier.classify(List.of("echo", "hello"))).isEqualTo(LoadLevel.MEDIUM); + assertThat(classifier.classify(List.of("/bin/bash", "-c", "ls"))).isEqualTo(LoadLevel.MEDIUM); + assertThat(classifier.classify(List.of("python3", "script.py"))).isEqualTo(LoadLevel.MEDIUM); + } + + @Test + void classify_withEmptyCommand_shouldReturnMedium() { + assertThat(classifier.classify(List.of())).isEqualTo(LoadLevel.MEDIUM); + } + + @Test + void classify_withNull_shouldThrowException() { + assertThatThrownBy(() -> classifier.classify(null)) + .isInstanceOf(NullPointerException.class); + } + } + + @Nested + class LoadingTests { + + @Test + void load_withAllFilesPresent_shouldLoadAllMatchers() throws IOException { + Files.writeString(tempDir.resolve("high.load"), "ffmpeg\n"); + Files.writeString(tempDir.resolve("medium.load"), "custom-tool\n"); + Files.writeString(tempDir.resolve("low.load"), "curl\n"); + + LoadLevelClassifier classifier = LoadLevelClassifier.load(tempDir); + + assertThat(classifier.classify(List.of("ffmpeg"))).isEqualTo(LoadLevel.HIGH); + assertThat(classifier.classify(List.of("custom-tool"))).isEqualTo(LoadLevel.MEDIUM); + assertThat(classifier.classify(List.of("curl"))).isEqualTo(LoadLevel.LOW); + } + + @Test + void load_withMissingFiles_shouldTreatAsEmpty() throws IOException { + // No load files exist + + LoadLevelClassifier classifier = LoadLevelClassifier.load(tempDir); + + // Everything should default to MEDIUM + assertThat(classifier.classify(List.of("ffmpeg"))).isEqualTo(LoadLevel.MEDIUM); + assertThat(classifier.classify(List.of("curl"))).isEqualTo(LoadLevel.MEDIUM); + } + + @Test + void load_withNullPath_shouldThrowException() { + assertThatThrownBy(() -> LoadLevelClassifier.load(null)) + .isInstanceOf(NullPointerException.class); + } + } + + @Nested + class PriorityTests { + + @Test + void classify_whenInMultipleLists_shouldPrioritizeHighOverLow() throws IOException { + // Put ffmpeg in both high and low + Files.writeString(tempDir.resolve("high.load"), "ffmpeg\n"); + Files.writeString(tempDir.resolve("low.load"), "ffmpeg\n"); + + LoadLevelClassifier classifier = LoadLevelClassifier.load(tempDir); + + // HIGH should win + assertThat(classifier.classify(List.of("ffmpeg"))).isEqualTo(LoadLevel.HIGH); + } + + @Test + void classify_whenInMediumAndLow_shouldPrioritizeMediumOverLow() throws IOException { + Files.writeString(tempDir.resolve("medium.load"), "curl\n"); + Files.writeString(tempDir.resolve("low.load"), "curl\n"); + + LoadLevelClassifier classifier = LoadLevelClassifier.load(tempDir); + + // MEDIUM should win over LOW + assertThat(classifier.classify(List.of("curl"))).isEqualTo(LoadLevel.MEDIUM); + } + } +} diff --git a/src/test/java/com/samsonmedia/barn/jobs/LoadLevelTest.java b/src/test/java/com/samsonmedia/barn/jobs/LoadLevelTest.java new file mode 100644 index 0000000..19e1b73 --- /dev/null +++ b/src/test/java/com/samsonmedia/barn/jobs/LoadLevelTest.java @@ -0,0 +1,90 @@ +package com.samsonmedia.barn.jobs; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +import org.junit.jupiter.api.Test; + +/** + * Tests for LoadLevel enum. + */ +class LoadLevelTest { + + @Test + void values_shouldContainAllLoadLevels() { + assertThat(LoadLevel.values()).containsExactly( + LoadLevel.HIGH, + LoadLevel.MEDIUM, + LoadLevel.LOW + ); + } + + @Test + void fromString_withValidLowercase_shouldReturnLoadLevel() { + assertThat(LoadLevel.fromString("high")).isEqualTo(LoadLevel.HIGH); + assertThat(LoadLevel.fromString("medium")).isEqualTo(LoadLevel.MEDIUM); + assertThat(LoadLevel.fromString("low")).isEqualTo(LoadLevel.LOW); + } + + @Test + void fromString_withValidUppercase_shouldReturnLoadLevel() { + assertThat(LoadLevel.fromString("HIGH")).isEqualTo(LoadLevel.HIGH); + assertThat(LoadLevel.fromString("MEDIUM")).isEqualTo(LoadLevel.MEDIUM); + assertThat(LoadLevel.fromString("LOW")).isEqualTo(LoadLevel.LOW); + } + + @Test + void fromString_withMixedCase_shouldReturnLoadLevel() { + assertThat(LoadLevel.fromString("High")).isEqualTo(LoadLevel.HIGH); + assertThat(LoadLevel.fromString("Medium")).isEqualTo(LoadLevel.MEDIUM); + assertThat(LoadLevel.fromString("Low")).isEqualTo(LoadLevel.LOW); + } + + @Test + void fromString_withWhitespace_shouldTrimAndParse() { + assertThat(LoadLevel.fromString(" high ")).isEqualTo(LoadLevel.HIGH); + assertThat(LoadLevel.fromString(" medium ")).isEqualTo(LoadLevel.MEDIUM); + } + + @Test + void fromString_withNull_shouldThrowException() { + assertThatThrownBy(() -> LoadLevel.fromString(null)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot be null or blank"); + } + + @Test + void fromString_withBlank_shouldThrowException() { + assertThatThrownBy(() -> LoadLevel.fromString(" ")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("cannot be null or blank"); + } + + @Test + void fromString_withInvalidValue_shouldThrowException() { + assertThatThrownBy(() -> LoadLevel.fromString("invalid")) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("Invalid load level") + .hasMessageContaining("invalid") + .hasMessageContaining("high, medium, low"); + } + + @Test + void toLowercase_shouldReturnLowercaseString() { + assertThat(LoadLevel.HIGH.toLowercase()).isEqualTo("high"); + assertThat(LoadLevel.MEDIUM.toLowercase()).isEqualTo("medium"); + assertThat(LoadLevel.LOW.toLowercase()).isEqualTo("low"); + } + + @Test + void getDefaultMaxJobs_shouldReturnCorrectDefaults() { + assertThat(LoadLevel.HIGH.getDefaultMaxJobs()).isEqualTo(2); + assertThat(LoadLevel.MEDIUM.getDefaultMaxJobs()).isEqualTo(8); + assertThat(LoadLevel.LOW.getDefaultMaxJobs()).isEqualTo(32); + } + + @Test + void getDefault_shouldReturnMedium() { + assertThat(LoadLevel.getDefault()).isEqualTo(LoadLevel.MEDIUM); + } +} diff --git a/src/test/java/com/samsonmedia/barn/jobs/RetryCalculatorTest.java b/src/test/java/com/samsonmedia/barn/jobs/RetryCalculatorTest.java index 953b977..f7fd6a6 100644 --- a/src/test/java/com/samsonmedia/barn/jobs/RetryCalculatorTest.java +++ b/src/test/java/com/samsonmedia/barn/jobs/RetryCalculatorTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.jobs; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -260,7 +261,8 @@ class RetryCalculatorTest { 12345L, Instant.now(), retryCount, - null + null, + MEDIUM ); } @@ -278,7 +280,8 @@ class RetryCalculatorTest { 12345L, Instant.now(), retryCount, - null + null, + MEDIUM ); } } diff --git a/src/test/java/com/samsonmedia/barn/logging/JobContextTest.java b/src/test/java/com/samsonmedia/barn/logging/JobContextTest.java index 4bccdcd..cdeffb2 100644 --- a/src/test/java/com/samsonmedia/barn/logging/JobContextTest.java +++ b/src/test/java/com/samsonmedia/barn/logging/JobContextTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.logging; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -183,7 +184,8 @@ class JobContextTest { null, // pid null, // heartbeat 0, // retryCount - null // retryAt + null, // retryAt + MEDIUM ); } } diff --git a/src/test/java/com/samsonmedia/barn/logging/JobLogEventsTest.java b/src/test/java/com/samsonmedia/barn/logging/JobLogEventsTest.java index 7a6769c..c7fcd1e 100644 --- a/src/test/java/com/samsonmedia/barn/logging/JobLogEventsTest.java +++ b/src/test/java/com/samsonmedia/barn/logging/JobLogEventsTest.java @@ -1,5 +1,6 @@ package com.samsonmedia.barn.logging; +import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM; import static org.assertj.core.api.Assertions.assertThatCode; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -200,7 +201,8 @@ class JobLogEventsTest { null, // pid null, // heartbeat 0, // retryCount - null // retryAt + null, // retryAt + MEDIUM ); } @@ -218,7 +220,8 @@ class JobLogEventsTest { pid, Instant.now(), // heartbeat 0, // retryCount - null // retryAt + null, // retryAt + MEDIUM ); } @@ -236,7 +239,8 @@ class JobLogEventsTest { null, // pid null, // heartbeat 0, // retryCount - null // retryAt + null, // retryAt + MEDIUM ); } } diff --git a/src/test/java/com/samsonmedia/barn/service/BarnServiceTest.java b/src/test/java/com/samsonmedia/barn/service/BarnServiceTest.java index 6dd5eff..b3b773c 100644 --- a/src/test/java/com/samsonmedia/barn/service/BarnServiceTest.java +++ b/src/test/java/com/samsonmedia/barn/service/BarnServiceTest.java @@ -14,6 +14,7 @@ import org.junit.jupiter.api.io.TempDir; import com.samsonmedia.barn.config.CleanupConfig; import com.samsonmedia.barn.config.Config; import com.samsonmedia.barn.config.JobsConfig; +import com.samsonmedia.barn.config.LoadLevelConfig; import com.samsonmedia.barn.config.LogLevel; import com.samsonmedia.barn.config.ServiceConfig; import com.samsonmedia.barn.config.StorageConfig; @@ -45,7 +46,8 @@ class BarnServiceTest { CleanupConfig cleanupConfig = new CleanupConfig(false, 60, 24, false, 168); StorageConfig storageConfig = new StorageConfig(tempDir, 50, false); - config = new Config(serviceConfig, jobsConfig, cleanupConfig, storageConfig); + config = new Config(serviceConfig, jobsConfig, cleanupConfig, storageConfig, + LoadLevelConfig.withDefaults()); } @Test