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 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Opus 4.5 committed 2026-01-24 14:33:06 +00:00
1 parent 5a213788c7
commit f233547ce8
52 files changed
+2444 -193

No files matched your search

@@ -16,7 +16,8 @@ import picocli.CommandLine.Spec;
subcommands = {
ConfigShowCommand.class,
ConfigValidateCommand.class,
ConfigInitCommand.class
ConfigInitCommand.class,
ConfigInstallCommand.class
}
)
public class ConfigCommand implements Runnable {
@@ -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.
*
* <p>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<String> 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);
}
}
}
@@ -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<Job> jobs) {
// Define columns
List<String> headers = List.of("ID", "STATE", "TAG", "CREATED", "EXIT");
List<String> headers = List.of("ID", "STATE", "LOAD", "TAG", "CREATED", "EXIT");
// Convert jobs to rows
List<List<String>> 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);
}
@@ -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);
}
@@ -19,10 +19,12 @@ import picocli.CommandLine.Option;
*
* <p>Supports platform-specific service installation:
* <ul>
* <li>macOS: launchd (LaunchDaemons/LaunchAgents)</li>
* <li>Linux: systemd (planned)</li>
* <li>Windows: Windows Service (planned)</li>
* <li>macOS: launchd (LaunchDaemons)</li>
* <li>Linux: systemd</li>
* <li>Windows: Windows Service</li>
* </ul>
*
* <p>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();
@@ -18,9 +18,11 @@ import picocli.CommandLine.Option;
* <p>Removes platform-specific service registration:
* <ul>
* <li>macOS: launchd plist files</li>
* <li>Linux: systemd unit files (planned)</li>
* <li>Windows: Windows Service registration (planned)</li>
* <li>Linux: systemd unit files</li>
* <li>Windows: Windows Service registration</li>
* </ul>
*
* <p>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;
@@ -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() : "-",
@@ -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.
*
* <p>Commands can be matched by:
* <ul>
* <li>Executable name only (e.g., "ffmpeg")</li>
* <li>Full path to executable (e.g., "/usr/local/bin/ffmpeg")</li>
* <li>Directory containing executables (e.g., "/opt/encoders/")</li>
* </ul>
*/
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<String> command);
/**
* Matches commands by executable name only.
*
* <p>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<String> 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.
*
* <p>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<String> command) {
if (command.isEmpty()) {
return false;
}
return Path.of(command.getFirst()).equals(path);
}
}
/**
* Matches commands whose executables are in the specified directory.
*
* <p>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<String> 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());
}
}
}
@@ -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()
);
}
}
@@ -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.
*
@@ -186,11 +186,17 @@ public final class ConfigLoader {
}
private Config buildConfig(Map<String, Map<String, Object>> data) {
// Handle both "load_levels" (from TOML) and "loadlevels" (from env vars)
Map<String, Object> 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<String, Object> 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> T getOrDefault(Map<String, Object> data, String key, T defaultValue,
Function<Object, T> converter) {
@@ -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).
*
* <p>Load files use a gitignore-like format:
* <ul>
* <li>Lines starting with # are comments</li>
* <li>Empty lines are ignored</li>
* <li>Plain names (e.g., "ffmpeg") match any executable with that name</li>
* <li>Full paths (e.g., "/usr/bin/ffmpeg") match that exact path</li>
* <li>Directories with trailing slash (e.g., "/opt/encoders/") match any executable in that directory</li>
* </ul>
*/
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<CommandMatcher> parse(Path path) throws IOException {
Objects.requireNonNull(path, "path must not be null");
List<String> lines = Files.readAllLines(path);
List<CommandMatcher> 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<CommandMatcher> 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);
}
}
@@ -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.
*
* <p>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).
*
* <p>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;
}
}
@@ -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);
}
@@ -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<LoadLevel, AtomicInteger> 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.
*
* <p>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<Job> nextJob = findNextQueued();
// Find next queued job that has capacity in its load level
Optional<Job> 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<Job> findNextQueued() throws IOException {
private Optional<Job> findNextQueuedWithCapacity() throws IOException {
List<Job> 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);
}
}
}
@@ -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<String> 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<String> 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);
}
/**
@@ -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<String> 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<String> 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<String> 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<String> 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
);
}
@@ -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<String> 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<String> 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
);
}
}
@@ -0,0 +1,83 @@
package com.samsonmedia.barn.jobs;
import java.util.Locale;
/**
* Load level classification for jobs.
*
* <p>Jobs are classified into load levels based on their resource intensity:
* <ul>
* <li>{@link #HIGH} - CPU/GPU intensive tasks like transcoding (default: 2 concurrent)</li>
* <li>{@link #MEDIUM} - General purpose tasks (default: 8 concurrent)</li>
* <li>{@link #LOW} - Network/IO intensive tasks like downloads (default: 32 concurrent)</li>
* </ul>
*/
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");
}
}
}
@@ -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.
*
* <p>The classifier loads whitelist files from the config directory:
* <ul>
* <li>{@code high.load} - Commands that are CPU/GPU intensive (e.g., transcoding)</li>
* <li>{@code medium.load} - General purpose commands</li>
* <li>{@code low.load} - Commands that are network/IO intensive (e.g., downloads)</li>
* </ul>
*
* <p>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<CommandMatcher> highMatchers;
private final List<CommandMatcher> mediumMatchers;
private final List<CommandMatcher> 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<CommandMatcher> highMatchers,
List<CommandMatcher> mediumMatchers,
List<CommandMatcher> 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.
*
* <p>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<CommandMatcher> high = LoadFileParser.parseIfExists(configDir.resolve(HIGH_LOAD_FILE));
List<CommandMatcher> medium = LoadFileParser.parseIfExists(configDir.resolve(MEDIUM_LOAD_FILE));
List<CommandMatcher> low = LoadFileParser.parseIfExists(configDir.resolve(LOW_LOAD_FILE));
return new LoadLevelClassifier(high, medium, low);
}
/**
* Loads a classifier from the system config directory.
*
* <p>Searches for whitelist files in the system config directory
* (e.g., /etc/barn/ on Linux/macOS, %PROGRAMDATA%\barn\ on Windows).
*
* <p>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.
*
* <p>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<String> 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();
}
}
@@ -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<String> command = (List<String>) 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;
}
@@ -3,7 +3,8 @@
"includes": [
{"pattern": "logback.xml"},
{"pattern": "version.properties"},
{"pattern": "META-INF/.*"}
{"pattern": "META-INF/.*"},
{"pattern": "defaults/.*"}
]
},
"bundles": []
+67
View File
@@ -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
+16
View File
@@ -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
+16
View File
@@ -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
+4
View File
@@ -0,0 +1,4 @@
# Medium load commands
# Maximum concurrent: 8 (default)
#
# Empty by default - unmatched commands are classified as MEDIUM
@@ -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
@@ -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");
}
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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");
}
}
@@ -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
);
}
}
@@ -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);
}
}
}
@@ -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<String, String> 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 {
@@ -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();
}
}
}
@@ -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<CommandMatcher> 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<CommandMatcher> 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<CommandMatcher> 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<CommandMatcher> 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<CommandMatcher> 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<CommandMatcher> 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<CommandMatcher> 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<CommandMatcher> 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<CommandMatcher> matchers = LoadFileParser.parseIfExists(loadFile);
assertThat(matchers).hasSize(1);
}
@Test
void parseIfExists_withNonExistentFile_shouldReturnEmptyList() {
Path nonExistent = tempDir.resolve("nonexistent.load");
List<CommandMatcher> matchers = LoadFileParser.parseIfExists(nonExistent);
assertThat(matchers).isEmpty();
}
}
@@ -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);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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
@@ -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();
}
@@ -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<Job> found = repository.findById(created.id());
assertThat(found).isPresent();
assertThat(found.get().loadLevel()).isEqualTo(LoadLevel.LOW);
}
}
@Nested
@@ -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
}
}
@@ -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);
}
}
}
@@ -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);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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
);
}
}
@@ -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