Archived
feat(service): add IPC communication and service management
Implement proper CLI-to-service communication via Unix domain sockets, fixing issue where CLI commands couldn't see jobs managed by the service. Key changes: - Add IPC client/server for CLI-service communication - Fix directory mismatch (CLI used java.io.tmpdir, service used /tmp/barn) - Add service management commands (start, stop, restart, reload, logs) - Add service installation for macOS (launchd), Linux (systemd), Windows - Add process usage monitoring (barn usage command) - Add job state breakdown in service status (succeeded, failed, canceled) - Add output formatters (human, JSON, XML) - Add crash recovery and heartbeat checking - Add structured logging with MDC context The CLI commands now properly communicate with the running service via IPC, ensuring consistent job state visibility. Fixes #24 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
818c45de0a
commit
92810cabee
103 files changed
+17457
-101
No files matched your search
@@ -36,6 +36,8 @@ public final class Main {
|
||||
* @return the exit code (0 for success, non-zero for failure)
|
||||
*/
|
||||
public static int run(String[] args) {
|
||||
return new CommandLine(new BarnCommand()).execute(args);
|
||||
CommandLine cmd = new CommandLine(new BarnCommand());
|
||||
cmd.setCaseInsensitiveEnumValuesAllowed(true);
|
||||
return cmd.execute(args);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import picocli.CommandLine.Spec;
|
||||
RunCommand.class,
|
||||
StatusCommand.class,
|
||||
DescribeCommand.class,
|
||||
UsageCommand.class,
|
||||
KillCommand.class,
|
||||
CleanCommand.class,
|
||||
ServiceCommand.class,
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.Callable;
|
||||
|
||||
import picocli.CommandLine.Mixin;
|
||||
import picocli.CommandLine.Model.CommandSpec;
|
||||
import picocli.CommandLine.Spec;
|
||||
|
||||
/**
|
||||
* Base class for all CLI commands.
|
||||
*
|
||||
* <p>Provides common functionality including global options,
|
||||
* output formatting, and error handling.
|
||||
*/
|
||||
public abstract class BaseCommand implements Callable<Integer> {
|
||||
|
||||
/** Exit code for successful execution. */
|
||||
protected static final int EXIT_SUCCESS = 0;
|
||||
|
||||
/** Exit code for general errors. */
|
||||
protected static final int EXIT_ERROR = 1;
|
||||
|
||||
/** Exit code for command-line usage errors. */
|
||||
protected static final int EXIT_USAGE = 2;
|
||||
|
||||
@Mixin
|
||||
protected GlobalOptions globalOptions;
|
||||
|
||||
@Spec
|
||||
protected CommandSpec spec;
|
||||
|
||||
/**
|
||||
* Gets the output formatter based on global options.
|
||||
*
|
||||
* @return the appropriate formatter
|
||||
*/
|
||||
protected OutputFormatter getFormatter() {
|
||||
if (globalOptions == null) {
|
||||
return OutputFormatter.forFormat(OutputFormat.HUMAN);
|
||||
}
|
||||
return OutputFormatter.forFormat(globalOptions.getOutputFormat());
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs a single value to stdout using the current formatter.
|
||||
*
|
||||
* @param value the value to output
|
||||
*/
|
||||
protected void output(Object value) {
|
||||
getOut().println(getFormatter().format(value));
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs a list of values to stdout using the current formatter.
|
||||
*
|
||||
* @param values the values to output
|
||||
*/
|
||||
protected void outputList(List<?> values) {
|
||||
getOut().println(getFormatter().formatList(values));
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs an error message to stderr using the current formatter.
|
||||
*
|
||||
* @param message the error message
|
||||
*/
|
||||
protected void outputError(String message) {
|
||||
outputError(message, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Outputs an error message with cause to stderr using the current formatter.
|
||||
*
|
||||
* @param message the error message
|
||||
* @param cause the optional cause
|
||||
*/
|
||||
protected void outputError(String message, Throwable cause) {
|
||||
getErr().println(getFormatter().formatError(message, cause));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the stdout writer.
|
||||
*
|
||||
* @return the stdout PrintWriter
|
||||
*/
|
||||
protected PrintWriter getOut() {
|
||||
return spec.commandLine().getOut();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the stderr writer.
|
||||
*
|
||||
* @return the stderr PrintWriter
|
||||
*/
|
||||
protected PrintWriter getErr() {
|
||||
return spec.commandLine().getErr();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if running in offline mode.
|
||||
*
|
||||
* @return true if offline mode is enabled
|
||||
*/
|
||||
protected boolean isOffline() {
|
||||
return globalOptions != null && globalOptions.isOffline();
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,392 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
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.state.BarnDirectories;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
import com.samsonmedia.barn.util.DurationParser;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Model.CommandSpec;
|
||||
import picocli.CommandLine.Spec;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to remove completed jobs.
|
||||
*
|
||||
* <p>Placeholder implementation - full implementation in ticket #13.
|
||||
*/
|
||||
@Command(
|
||||
name = "clean",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Remove completed jobs"
|
||||
)
|
||||
public class CleanCommand implements Runnable {
|
||||
public class CleanCommand extends BaseCommand {
|
||||
|
||||
@Spec
|
||||
private CommandSpec spec;
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CleanCommand.class);
|
||||
|
||||
@Option(names = {"--all"}, description = "Remove all completed jobs regardless of age")
|
||||
private boolean all;
|
||||
|
||||
@Option(names = {"--older-than"}, description = "Remove jobs older than duration (e.g., 24h, 7d)")
|
||||
private String olderThan;
|
||||
|
||||
@Option(names = {"--include-failed"}, description = "Also remove failed jobs")
|
||||
private boolean includeFailed;
|
||||
|
||||
@Option(names = {"--dry-run"}, description = "Show what would be removed without removing")
|
||||
private boolean dryRun;
|
||||
|
||||
@Option(names = {"--job-id"}, description = "Remove specific job")
|
||||
private String jobId;
|
||||
|
||||
@Option(names = {"--barn-dir"}, description = "Barn data directory", hidden = true)
|
||||
private Path barnDir;
|
||||
|
||||
/**
|
||||
* Sets the barn directory (for testing).
|
||||
*
|
||||
* @param barnDir the barn directory path
|
||||
*/
|
||||
public void setBarnDir(Path barnDir) {
|
||||
this.barnDir = barnDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
spec.commandLine().getOut().println("Clean command not yet implemented");
|
||||
public Integer call() {
|
||||
if (isOffline()) {
|
||||
return runOffline();
|
||||
}
|
||||
return runWithService();
|
||||
}
|
||||
|
||||
private int runOffline() {
|
||||
try {
|
||||
BarnDirectories dirs = getBarnDirectories();
|
||||
JobRepository repository = new JobRepository(dirs);
|
||||
|
||||
// If specific job requested
|
||||
if (jobId != null) {
|
||||
return cleanSpecificJob(repository, dirs);
|
||||
}
|
||||
|
||||
// Get all jobs
|
||||
List<Job> jobs = repository.findAll();
|
||||
|
||||
// Filter to cleanable jobs
|
||||
List<Job> toClean = filterCleanableJobs(jobs);
|
||||
|
||||
// Apply age filter if specified
|
||||
if (olderThan != null) {
|
||||
Duration maxAge = DurationParser.parse(olderThan);
|
||||
toClean = filterByAge(toClean, maxAge);
|
||||
}
|
||||
|
||||
// If not --all and no --older-than, default to keeping jobs
|
||||
if (!all && olderThan == null) {
|
||||
// Without --all or --older-than, don't clean anything
|
||||
toClean = List.of();
|
||||
}
|
||||
|
||||
// Clean or dry-run
|
||||
List<CleanedJob> cleaned = new ArrayList<>();
|
||||
long totalSize = 0;
|
||||
|
||||
for (Job job : toClean) {
|
||||
long size = calculateJobSize(dirs, job.id());
|
||||
cleaned.add(new CleanedJob(job, size));
|
||||
totalSize += size;
|
||||
|
||||
if (!dryRun) {
|
||||
repository.delete(job.id());
|
||||
LOG.info("Cleaned job: {}", job.id());
|
||||
}
|
||||
}
|
||||
|
||||
// Output
|
||||
outputCleanResult(cleaned, totalSize);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to clean jobs", e);
|
||||
return EXIT_ERROR;
|
||||
} catch (IllegalArgumentException e) {
|
||||
outputError(e.getMessage());
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int cleanSpecificJob(JobRepository repository, BarnDirectories dirs) throws IOException {
|
||||
Optional<Job> jobOpt = repository.findById(jobId);
|
||||
if (jobOpt.isEmpty()) {
|
||||
outputError("Job not found: " + jobId);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
Job job = jobOpt.get();
|
||||
if (!isCleanable(job)) {
|
||||
outputError("Cannot clean job (state: " + job.state().toLowercase() + ")");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
long size = calculateJobSize(dirs, job.id());
|
||||
List<CleanedJob> cleaned = List.of(new CleanedJob(job, size));
|
||||
|
||||
if (!dryRun) {
|
||||
repository.delete(jobId);
|
||||
LOG.info("Cleaned job: {}", jobId);
|
||||
}
|
||||
|
||||
outputCleanResult(cleaned, size);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
private int runWithService() {
|
||||
try (IpcClient client = new IpcClient(getBarnDirectories().getSocketPath())) {
|
||||
// Build request payload
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("all", all);
|
||||
payload.put("includeFailed", includeFailed);
|
||||
payload.put("dryRun", dryRun);
|
||||
if (olderThan != null) {
|
||||
payload.put("olderThan", olderThan);
|
||||
}
|
||||
if (jobId != null) {
|
||||
payload.put("jobId", jobId);
|
||||
}
|
||||
|
||||
// Send request and get response
|
||||
Object response = client.send("clean_jobs", payload, Object.class);
|
||||
|
||||
// Convert response
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> resultMap = (Map<String, Object>) response;
|
||||
List<Job> jobs = mapper.convertValue(resultMap.get("jobs"), new TypeReference<List<Job>>() { });
|
||||
|
||||
// Build cleaned job list (without size info from IPC)
|
||||
List<CleanedJob> cleaned = jobs.stream()
|
||||
.map(j -> new CleanedJob(j, 0))
|
||||
.toList();
|
||||
|
||||
outputCleanResult(cleaned, 0);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IpcException e) {
|
||||
if ("SERVICE_NOT_RUNNING".equals(e.getCode())) {
|
||||
outputError("Service not running. Start with: barn service start\n"
|
||||
+ "Or use --offline to run without the service.");
|
||||
} else {
|
||||
outputError("IPC error: " + e.getMessage());
|
||||
}
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private BarnDirectories getBarnDirectories() {
|
||||
if (barnDir != null) {
|
||||
return new BarnDirectories(barnDir);
|
||||
}
|
||||
Path defaultDir = ConfigDefaults.getDefaultBaseDir();
|
||||
return new BarnDirectories(defaultDir);
|
||||
}
|
||||
|
||||
private List<Job> filterCleanableJobs(List<Job> jobs) {
|
||||
return jobs.stream()
|
||||
.filter(this::isCleanable)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private boolean isCleanable(Job job) {
|
||||
// Never clean running or queued jobs
|
||||
if (job.state() == JobState.RUNNING || job.state() == JobState.QUEUED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Failed jobs only cleaned with --include-failed
|
||||
if (job.state() == JobState.FAILED && !includeFailed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Succeeded and canceled are always cleanable
|
||||
return true;
|
||||
}
|
||||
|
||||
private List<Job> filterByAge(List<Job> jobs, Duration maxAge) {
|
||||
Instant cutoff = Instant.now().minus(maxAge);
|
||||
return jobs.stream()
|
||||
.filter(job -> {
|
||||
Instant finishedAt = job.finishedAt();
|
||||
if (finishedAt == null) {
|
||||
finishedAt = job.createdAt();
|
||||
}
|
||||
return finishedAt.isBefore(cutoff);
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
|
||||
private long calculateJobSize(BarnDirectories dirs, String id) throws IOException {
|
||||
Path jobDir = dirs.getJobDir(id);
|
||||
if (!Files.exists(jobDir)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
try (Stream<Path> walk = Files.walk(jobDir)) {
|
||||
return walk
|
||||
.filter(Files::isRegularFile)
|
||||
.mapToLong(p -> {
|
||||
try {
|
||||
return Files.size(p);
|
||||
} catch (IOException e) {
|
||||
return 0;
|
||||
}
|
||||
})
|
||||
.sum();
|
||||
}
|
||||
}
|
||||
|
||||
private void outputCleanResult(List<CleanedJob> cleaned, long totalSize) {
|
||||
OutputFormat format = globalOptions != null
|
||||
? globalOptions.getOutputFormat()
|
||||
: OutputFormat.HUMAN;
|
||||
|
||||
switch (format) {
|
||||
case HUMAN -> outputHumanFormat(cleaned, totalSize);
|
||||
case JSON -> outputJsonFormat(cleaned, totalSize);
|
||||
case XML -> outputXmlFormat(cleaned, totalSize);
|
||||
default -> outputHumanFormat(cleaned, totalSize);
|
||||
}
|
||||
}
|
||||
|
||||
private void outputHumanFormat(List<CleanedJob> cleaned, long totalSize) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
String prefix = dryRun ? "Would clean" : "Cleaned";
|
||||
|
||||
if (cleaned.isEmpty()) {
|
||||
sb.append(prefix).append(" 0 jobs.");
|
||||
} else {
|
||||
sb.append(prefix).append(" ").append(cleaned.size()).append(" job");
|
||||
if (cleaned.size() != 1) {
|
||||
sb.append("s");
|
||||
}
|
||||
sb.append(":\n");
|
||||
|
||||
for (CleanedJob cj : cleaned) {
|
||||
sb.append(" ").append(cj.job.id())
|
||||
.append(" (").append(cj.job.state().toLowercase())
|
||||
.append(", ").append(formatAge(cj.job))
|
||||
.append(")");
|
||||
if (dryRun) {
|
||||
sb.append(" - ").append(formatSize(cj.size));
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
|
||||
sb.append("\n");
|
||||
if (dryRun) {
|
||||
sb.append("Would free: ").append(formatSize(totalSize));
|
||||
} else {
|
||||
sb.append("Disk space freed: ").append(formatSize(totalSize));
|
||||
}
|
||||
}
|
||||
|
||||
getOut().println(sb.toString());
|
||||
}
|
||||
|
||||
private void outputJsonFormat(List<CleanedJob> cleaned, long totalSize) {
|
||||
Map<String, Object> response = buildResponseMap(cleaned, totalSize);
|
||||
output(response);
|
||||
}
|
||||
|
||||
private void outputXmlFormat(List<CleanedJob> cleaned, long totalSize) {
|
||||
Map<String, Object> response = buildResponseMap(cleaned, totalSize);
|
||||
output(response);
|
||||
}
|
||||
|
||||
private Map<String, Object> buildResponseMap(List<CleanedJob> cleaned, long totalSize) {
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
|
||||
List<Map<String, Object>> cleanedList = cleaned.stream()
|
||||
.map(cj -> {
|
||||
Map<String, Object> item = new LinkedHashMap<>();
|
||||
item.put("id", cj.job.id());
|
||||
item.put("state", cj.job.state().toLowercase());
|
||||
item.put("ageHours", calculateAgeHours(cj.job));
|
||||
item.put("sizeBytes", cj.size);
|
||||
return item;
|
||||
})
|
||||
.toList();
|
||||
|
||||
response.put("cleaned", cleanedList);
|
||||
response.put("count", cleaned.size());
|
||||
response.put("bytesFreed", totalSize);
|
||||
response.put("dryRun", dryRun);
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private String formatAge(Job job) {
|
||||
Instant finished = job.finishedAt();
|
||||
if (finished == null) {
|
||||
finished = job.createdAt();
|
||||
}
|
||||
Duration age = Duration.between(finished, Instant.now());
|
||||
|
||||
long hours = age.toHours();
|
||||
if (hours < 24) {
|
||||
return hours + " hours old";
|
||||
}
|
||||
long days = age.toDays();
|
||||
return days + " day" + (days != 1 ? "s" : "") + " old";
|
||||
}
|
||||
|
||||
private long calculateAgeHours(Job job) {
|
||||
Instant finished = job.finishedAt();
|
||||
if (finished == null) {
|
||||
finished = job.createdAt();
|
||||
}
|
||||
return Duration.between(finished, Instant.now()).toHours();
|
||||
}
|
||||
|
||||
private String formatSize(long bytes) {
|
||||
if (bytes < 1024) {
|
||||
return bytes + " B";
|
||||
}
|
||||
if (bytes < 1024 * 1024) {
|
||||
return bytes / 1024 + " KB";
|
||||
}
|
||||
if (bytes < 1024L * 1024 * 1024) {
|
||||
return bytes / (1024 * 1024) + " MB";
|
||||
}
|
||||
return String.format("%.1f GB", bytes / (1024.0 * 1024 * 1024));
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper record for cleaned job information.
|
||||
*/
|
||||
private record CleanedJob(Job job, long size) { }
|
||||
}
|
||||
@@ -7,12 +7,17 @@ import picocli.CommandLine.Spec;
|
||||
/**
|
||||
* Command for configuration management.
|
||||
*
|
||||
* <p>Placeholder implementation - full implementation in ticket #21.
|
||||
* <p>Provides subcommands for viewing, validating, and initializing configuration.
|
||||
*/
|
||||
@Command(
|
||||
name = "config",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Configuration management"
|
||||
description = "Configuration management",
|
||||
subcommands = {
|
||||
ConfigShowCommand.class,
|
||||
ConfigValidateCommand.class,
|
||||
ConfigInitCommand.class
|
||||
}
|
||||
)
|
||||
public class ConfigCommand implements Runnable {
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import com.samsonmedia.barn.config.CleanupConfig;
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.config.ServiceConfig;
|
||||
import com.samsonmedia.barn.config.StorageConfig;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to create a default configuration file.
|
||||
*/
|
||||
@Command(
|
||||
name = "init",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Create default configuration file"
|
||||
)
|
||||
public class ConfigInitCommand extends BaseCommand {
|
||||
|
||||
@Option(names = {"--path", "-p"}, description = "Output path for config file")
|
||||
private Path outputPath;
|
||||
|
||||
@Option(names = {"--force", "-f"}, description = "Overwrite existing file")
|
||||
private boolean force;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
Path targetPath = outputPath != null
|
||||
? outputPath
|
||||
: ConfigDefaults.getUserConfigPath();
|
||||
|
||||
if (Files.exists(targetPath) && !force) {
|
||||
outputError("Configuration file already exists: " + targetPath);
|
||||
outputError("Use --force to overwrite");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
try {
|
||||
// Create parent directories if needed
|
||||
Path parent = targetPath.getParent();
|
||||
if (parent != null && !Files.exists(parent)) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
|
||||
String content = generateDefaultConfig();
|
||||
Files.writeString(targetPath, content);
|
||||
|
||||
getOut().println("Configuration file created: " + targetPath);
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to create configuration file: " + e.getMessage());
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private String generateDefaultConfig() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
sb.append("# Barn Configuration\n");
|
||||
sb.append("# See docs/config.md for full documentation\n");
|
||||
sb.append("\n");
|
||||
|
||||
// Service section
|
||||
sb.append("[service]\n");
|
||||
sb.append("# Logging verbosity: debug, info, warn, error\n");
|
||||
sb.append(String.format("log_level = \"%s\"%n",
|
||||
ServiceConfig.DEFAULT_LOG_LEVEL.toString().toLowerCase()));
|
||||
sb.append("\n");
|
||||
sb.append("# Maximum jobs running simultaneously\n");
|
||||
sb.append(String.format("max_concurrent_jobs = %d%n", ServiceConfig.DEFAULT_MAX_CONCURRENT_JOBS));
|
||||
sb.append("\n");
|
||||
sb.append("# Interval in seconds between heartbeat updates for running jobs\n");
|
||||
sb.append(String.format("heartbeat_interval_seconds = %d%n",
|
||||
ServiceConfig.DEFAULT_HEARTBEAT_INTERVAL_SECONDS));
|
||||
sb.append("\n");
|
||||
sb.append("# IPC socket path for CLI communication\n");
|
||||
sb.append(String.format("ipc_socket = \"%s\"%n", ConfigDefaults.getDefaultIpcSocket()));
|
||||
sb.append("\n");
|
||||
sb.append("# Time in seconds after which a job without heartbeat is considered stale\n");
|
||||
sb.append(String.format("stale_heartbeat_threshold_seconds = %d%n",
|
||||
ServiceConfig.DEFAULT_STALE_HEARTBEAT_THRESHOLD_SECONDS));
|
||||
sb.append("\n");
|
||||
|
||||
// Jobs section
|
||||
sb.append("[jobs]\n");
|
||||
sb.append("# Default timeout for jobs in seconds (1 hour)\n");
|
||||
sb.append(String.format("default_timeout_seconds = %d%n", JobsConfig.DEFAULT_TIMEOUT_SECONDS));
|
||||
sb.append("\n");
|
||||
sb.append("# Maximum number of retry attempts for failed jobs\n");
|
||||
sb.append(String.format("max_retries = %d%n", JobsConfig.DEFAULT_MAX_RETRIES));
|
||||
sb.append("\n");
|
||||
sb.append("# Initial delay before first retry in seconds\n");
|
||||
sb.append(String.format("retry_delay_seconds = %d%n", JobsConfig.DEFAULT_RETRY_DELAY_SECONDS));
|
||||
sb.append("\n");
|
||||
sb.append("# Multiplier applied to delay after each retry (exponential backoff)\n");
|
||||
sb.append(String.format("retry_backoff_multiplier = %.1f%n", JobsConfig.DEFAULT_RETRY_BACKOFF_MULTIPLIER));
|
||||
sb.append("\n");
|
||||
sb.append("# Only retry on these exit codes (empty = retry all non-zero)\n");
|
||||
sb.append("retry_on_exit_codes = []\n");
|
||||
sb.append("\n");
|
||||
|
||||
// Cleanup section
|
||||
sb.append("[cleanup]\n");
|
||||
sb.append("# Enable automatic cleanup of old jobs\n");
|
||||
sb.append(String.format("enabled = %b%n", CleanupConfig.DEFAULT_ENABLED));
|
||||
sb.append("\n");
|
||||
sb.append("# Maximum age in hours for completed jobs before cleanup\n");
|
||||
sb.append(String.format("max_age_hours = %d%n", CleanupConfig.DEFAULT_MAX_AGE_HOURS));
|
||||
sb.append("\n");
|
||||
sb.append("# Interval in minutes between cleanup runs\n");
|
||||
sb.append(String.format("cleanup_interval_minutes = %d%n", CleanupConfig.DEFAULT_CLEANUP_INTERVAL_MINUTES));
|
||||
sb.append("\n");
|
||||
sb.append("# Keep failed jobs longer than successful ones\n");
|
||||
sb.append(String.format("keep_failed_jobs = %b%n", CleanupConfig.DEFAULT_KEEP_FAILED_JOBS));
|
||||
sb.append("\n");
|
||||
sb.append("# Maximum age in hours for failed jobs\n");
|
||||
sb.append(String.format("keep_failed_jobs_hours = %d%n", CleanupConfig.DEFAULT_KEEP_FAILED_JOBS_HOURS));
|
||||
sb.append("\n");
|
||||
|
||||
// Storage section
|
||||
sb.append("[storage]\n");
|
||||
sb.append("# Base directory for job data\n");
|
||||
sb.append(String.format("base_dir = \"%s\"%n", ConfigDefaults.getDefaultBaseDir()));
|
||||
sb.append("\n");
|
||||
sb.append("# Maximum disk usage in GB before warnings\n");
|
||||
sb.append(String.format("max_disk_usage_gb = %d%n", StorageConfig.DEFAULT_MAX_DISK_USAGE_GB));
|
||||
sb.append("\n");
|
||||
sb.append("# Preserve job working directories after completion (for debugging)\n");
|
||||
sb.append(String.format("preserve_work_dir = %b%n", StorageConfig.DEFAULT_PRESERVE_WORK_DIR));
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.samsonmedia.barn.config.Config;
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.config.ConfigLoader;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to show effective configuration.
|
||||
*/
|
||||
@Command(
|
||||
name = "show",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Show effective configuration"
|
||||
)
|
||||
public class ConfigShowCommand extends BaseCommand {
|
||||
|
||||
@Option(names = {"--defaults"}, description = "Show only default values")
|
||||
private boolean showDefaults;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
try {
|
||||
Config config;
|
||||
Path effectiveConfigFile = null;
|
||||
|
||||
if (showDefaults) {
|
||||
config = Config.withDefaults();
|
||||
} else {
|
||||
ConfigLoader loader = new ConfigLoader();
|
||||
Optional<Path> explicitPath = globalOptions != null
|
||||
? globalOptions.getConfigPath()
|
||||
: Optional.empty();
|
||||
config = loader.load(explicitPath);
|
||||
effectiveConfigFile = findConfigFile(explicitPath);
|
||||
}
|
||||
|
||||
OutputFormat format = globalOptions != null
|
||||
? globalOptions.getOutputFormat()
|
||||
: OutputFormat.HUMAN;
|
||||
|
||||
switch (format) {
|
||||
case HUMAN -> outputHumanFormat(config, effectiveConfigFile);
|
||||
case JSON -> output(toMap(config));
|
||||
case XML -> output(toMap(config));
|
||||
default -> outputHumanFormat(config, effectiveConfigFile);
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (ConfigLoader.ConfigException e) {
|
||||
outputError("Failed to load configuration: " + e.getMessage());
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private Path findConfigFile(Optional<Path> explicitPath) {
|
||||
if (explicitPath.isPresent() && Files.exists(explicitPath.get())) {
|
||||
return explicitPath.get();
|
||||
}
|
||||
for (Path path : ConfigDefaults.getConfigSearchPaths()) {
|
||||
if (Files.exists(path)) {
|
||||
return path;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void outputHumanFormat(Config config, Path configFile) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
sb.append("Barn Configuration\n");
|
||||
sb.append("==================\n");
|
||||
if (configFile != null) {
|
||||
sb.append("Config file: ").append(configFile).append("\n");
|
||||
} else if (showDefaults) {
|
||||
sb.append("Showing default values\n");
|
||||
} else {
|
||||
sb.append("Config file: (none found, using defaults)\n");
|
||||
}
|
||||
sb.append("\n");
|
||||
|
||||
// Service section
|
||||
sb.append("[service]\n");
|
||||
sb.append(String.format("log_level = %s%n", config.service().logLevel().toString().toLowerCase()));
|
||||
sb.append(String.format("max_concurrent_jobs = %d%n", config.service().maxConcurrentJobs()));
|
||||
sb.append(String.format("heartbeat_interval_seconds = %d%n", config.service().heartbeatIntervalSeconds()));
|
||||
sb.append(String.format("ipc_socket = %s%n", config.service().ipcSocket()));
|
||||
sb.append(String.format("stale_heartbeat_threshold_seconds = %d%n",
|
||||
config.service().staleHeartbeatThresholdSeconds()));
|
||||
sb.append("\n");
|
||||
|
||||
// Jobs section
|
||||
sb.append("[jobs]\n");
|
||||
sb.append(String.format("default_timeout_seconds = %d%n", config.jobs().defaultTimeoutSeconds()));
|
||||
sb.append(String.format("max_retries = %d%n", config.jobs().maxRetries()));
|
||||
sb.append(String.format("retry_delay_seconds = %d%n", config.jobs().retryDelaySeconds()));
|
||||
sb.append(String.format("retry_backoff_multiplier = %.1f%n", config.jobs().retryBackoffMultiplier()));
|
||||
sb.append(String.format("retry_on_exit_codes = %s%n", config.jobs().retryOnExitCodes()));
|
||||
sb.append("\n");
|
||||
|
||||
// Cleanup section
|
||||
sb.append("[cleanup]\n");
|
||||
sb.append(String.format("enabled = %b%n", config.cleanup().enabled()));
|
||||
sb.append(String.format("max_age_hours = %d%n", config.cleanup().maxAgeHours()));
|
||||
sb.append(String.format("cleanup_interval_minutes = %d%n", config.cleanup().cleanupIntervalMinutes()));
|
||||
sb.append(String.format("keep_failed_jobs = %b%n", config.cleanup().keepFailedJobs()));
|
||||
sb.append(String.format("keep_failed_jobs_hours = %d%n", config.cleanup().keepFailedJobsHours()));
|
||||
sb.append("\n");
|
||||
|
||||
// Storage section
|
||||
sb.append("[storage]\n");
|
||||
sb.append(String.format("base_dir = %s%n", config.storage().baseDir()));
|
||||
sb.append(String.format("max_disk_usage_gb = %d%n", config.storage().maxDiskUsageGb()));
|
||||
sb.append(String.format("preserve_work_dir = %b%n", config.storage().preserveWorkDir()));
|
||||
|
||||
getOut().println(sb.toString().trim());
|
||||
}
|
||||
|
||||
private Map<String, Object> toMap(Config config) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("service", buildServiceSection(config));
|
||||
map.put("jobs", buildJobsSection(config));
|
||||
map.put("cleanup", buildCleanupSection(config));
|
||||
map.put("storage", buildStorageSection(config));
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<String, Object> buildServiceSection(Config config) {
|
||||
Map<String, Object> service = new LinkedHashMap<>();
|
||||
service.put("log_level", config.service().logLevel().toString().toLowerCase());
|
||||
service.put("max_concurrent_jobs", config.service().maxConcurrentJobs());
|
||||
service.put("heartbeat_interval_seconds", config.service().heartbeatIntervalSeconds());
|
||||
service.put("ipc_socket", config.service().ipcSocket().toString());
|
||||
service.put("stale_heartbeat_threshold_seconds", config.service().staleHeartbeatThresholdSeconds());
|
||||
return service;
|
||||
}
|
||||
|
||||
private Map<String, Object> buildJobsSection(Config config) {
|
||||
Map<String, Object> jobs = new LinkedHashMap<>();
|
||||
jobs.put("default_timeout_seconds", config.jobs().defaultTimeoutSeconds());
|
||||
jobs.put("max_retries", config.jobs().maxRetries());
|
||||
jobs.put("retry_delay_seconds", config.jobs().retryDelaySeconds());
|
||||
jobs.put("retry_backoff_multiplier", config.jobs().retryBackoffMultiplier());
|
||||
jobs.put("retry_on_exit_codes", config.jobs().retryOnExitCodes());
|
||||
return jobs;
|
||||
}
|
||||
|
||||
private Map<String, Object> buildCleanupSection(Config config) {
|
||||
Map<String, Object> cleanup = new LinkedHashMap<>();
|
||||
cleanup.put("enabled", config.cleanup().enabled());
|
||||
cleanup.put("max_age_hours", config.cleanup().maxAgeHours());
|
||||
cleanup.put("cleanup_interval_minutes", config.cleanup().cleanupIntervalMinutes());
|
||||
cleanup.put("keep_failed_jobs", config.cleanup().keepFailedJobs());
|
||||
cleanup.put("keep_failed_jobs_hours", config.cleanup().keepFailedJobsHours());
|
||||
return cleanup;
|
||||
}
|
||||
|
||||
private Map<String, Object> buildStorageSection(Config config) {
|
||||
Map<String, Object> storage = new LinkedHashMap<>();
|
||||
storage.put("base_dir", config.storage().baseDir().toString());
|
||||
storage.put("max_disk_usage_gb", config.storage().maxDiskUsageGb());
|
||||
storage.put("preserve_work_dir", config.storage().preserveWorkDir());
|
||||
return storage;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import com.samsonmedia.barn.config.LogLevel;
|
||||
import com.samsonmedia.barn.config.TomlParser;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to validate a configuration file.
|
||||
*/
|
||||
@Command(
|
||||
name = "validate",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Validate configuration file"
|
||||
)
|
||||
public class ConfigValidateCommand extends BaseCommand {
|
||||
|
||||
private static final Set<String> KNOWN_SECTIONS = Set.of("service", "jobs", "cleanup", "storage");
|
||||
private static final Set<String> SERVICE_KEYS = Set.of(
|
||||
"log_level", "max_concurrent_jobs", "heartbeat_interval_seconds",
|
||||
"ipc_socket", "stale_heartbeat_threshold_seconds"
|
||||
);
|
||||
private static final Set<String> JOBS_KEYS = Set.of(
|
||||
"default_timeout_seconds", "max_retries", "retry_delay_seconds",
|
||||
"retry_backoff_multiplier", "retry_on_exit_codes"
|
||||
);
|
||||
private static final Set<String> CLEANUP_KEYS = Set.of(
|
||||
"enabled", "max_age_hours", "cleanup_interval_minutes",
|
||||
"keep_failed_jobs", "keep_failed_jobs_hours"
|
||||
);
|
||||
private static final Set<String> STORAGE_KEYS = Set.of(
|
||||
"base_dir", "max_disk_usage_gb", "preserve_work_dir"
|
||||
);
|
||||
|
||||
@Option(names = {"--file", "-f"}, description = "Config file to validate", required = true)
|
||||
private Path configFile;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
if (!Files.exists(configFile)) {
|
||||
outputError("Configuration file not found: " + configFile);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
List<ValidationError> errors = validate(configFile);
|
||||
|
||||
if (errors.isEmpty()) {
|
||||
getOut().println("Configuration is valid: " + configFile);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
OutputFormat format = globalOptions != null
|
||||
? globalOptions.getOutputFormat()
|
||||
: OutputFormat.HUMAN;
|
||||
|
||||
switch (format) {
|
||||
case HUMAN -> outputHumanFormat(errors);
|
||||
case JSON, XML -> output(toMap(errors));
|
||||
default -> outputHumanFormat(errors);
|
||||
}
|
||||
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
private List<ValidationError> validate(Path path) {
|
||||
List<ValidationError> errors = new ArrayList<>();
|
||||
|
||||
try {
|
||||
String content = Files.readString(path);
|
||||
Map<String, Map<String, Object>> data = TomlParser.parse(content);
|
||||
|
||||
// Check for unknown sections
|
||||
for (String section : data.keySet()) {
|
||||
if (!KNOWN_SECTIONS.contains(section)) {
|
||||
errors.add(new ValidationError(0, section, "Unknown section: [" + section + "]"));
|
||||
}
|
||||
}
|
||||
|
||||
// Validate service section
|
||||
if (data.containsKey("service")) {
|
||||
validateSection(data.get("service"), "service", SERVICE_KEYS, errors);
|
||||
validateServiceValues(data.get("service"), errors);
|
||||
}
|
||||
|
||||
// Validate jobs section
|
||||
if (data.containsKey("jobs")) {
|
||||
validateSection(data.get("jobs"), "jobs", JOBS_KEYS, errors);
|
||||
validateJobsValues(data.get("jobs"), errors);
|
||||
}
|
||||
|
||||
// Validate cleanup section
|
||||
if (data.containsKey("cleanup")) {
|
||||
validateSection(data.get("cleanup"), "cleanup", CLEANUP_KEYS, errors);
|
||||
validateCleanupValues(data.get("cleanup"), errors);
|
||||
}
|
||||
|
||||
// Validate storage section
|
||||
if (data.containsKey("storage")) {
|
||||
validateSection(data.get("storage"), "storage", STORAGE_KEYS, errors);
|
||||
validateStorageValues(data.get("storage"), errors);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
errors.add(new ValidationError(0, null, "Failed to read file: " + e.getMessage()));
|
||||
} catch (TomlParser.TomlParseException e) {
|
||||
errors.add(new ValidationError(0, null, "Parse error: " + e.getMessage()));
|
||||
}
|
||||
|
||||
return errors;
|
||||
}
|
||||
|
||||
private void validateSection(Map<String, Object> section, String sectionName,
|
||||
Set<String> knownKeys, List<ValidationError> errors) {
|
||||
for (String key : section.keySet()) {
|
||||
if (!knownKeys.contains(key)) {
|
||||
errors.add(new ValidationError(0, key,
|
||||
"Unknown key '" + key + "' in [" + sectionName + "] section"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateServiceValues(Map<String, Object> service, List<ValidationError> errors) {
|
||||
if (service.containsKey("log_level")) {
|
||||
Object value = service.get("log_level");
|
||||
try {
|
||||
LogLevel.fromString(value.toString());
|
||||
} catch (IllegalArgumentException e) {
|
||||
errors.add(new ValidationError(0, "log_level",
|
||||
"Invalid value for 'log_level': must be one of debug, info, warn, error"));
|
||||
}
|
||||
}
|
||||
|
||||
validatePositiveInteger(service, "max_concurrent_jobs", errors);
|
||||
validatePositiveInteger(service, "heartbeat_interval_seconds", errors);
|
||||
validatePositiveInteger(service, "stale_heartbeat_threshold_seconds", errors);
|
||||
}
|
||||
|
||||
private void validateJobsValues(Map<String, Object> jobs, List<ValidationError> errors) {
|
||||
validatePositiveInteger(jobs, "default_timeout_seconds", errors);
|
||||
validateNonNegativeInteger(jobs, "max_retries", errors);
|
||||
validateNonNegativeInteger(jobs, "retry_delay_seconds", errors);
|
||||
|
||||
if (jobs.containsKey("retry_backoff_multiplier")) {
|
||||
Object value = jobs.get("retry_backoff_multiplier");
|
||||
try {
|
||||
double multiplier = toDouble(value);
|
||||
if (multiplier < 1.0) {
|
||||
errors.add(new ValidationError(0, "retry_backoff_multiplier",
|
||||
"Invalid value for 'retry_backoff_multiplier': must be at least 1.0"));
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
errors.add(new ValidationError(0, "retry_backoff_multiplier",
|
||||
"Invalid value for 'retry_backoff_multiplier': must be a number"));
|
||||
}
|
||||
}
|
||||
|
||||
if (jobs.containsKey("retry_on_exit_codes")) {
|
||||
Object value = jobs.get("retry_on_exit_codes");
|
||||
if (!(value instanceof List)) {
|
||||
errors.add(new ValidationError(0, "retry_on_exit_codes",
|
||||
"Invalid value for 'retry_on_exit_codes': must be a list"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateCleanupValues(Map<String, Object> cleanup, List<ValidationError> errors) {
|
||||
validateBoolean(cleanup, "enabled", errors);
|
||||
validatePositiveInteger(cleanup, "max_age_hours", errors);
|
||||
validatePositiveInteger(cleanup, "cleanup_interval_minutes", errors);
|
||||
validateBoolean(cleanup, "keep_failed_jobs", errors);
|
||||
validatePositiveInteger(cleanup, "keep_failed_jobs_hours", errors);
|
||||
}
|
||||
|
||||
private void validateStorageValues(Map<String, Object> storage, List<ValidationError> errors) {
|
||||
validatePositiveInteger(storage, "max_disk_usage_gb", errors);
|
||||
validateBoolean(storage, "preserve_work_dir", errors);
|
||||
}
|
||||
|
||||
private void validatePositiveInteger(Map<String, Object> section, String key,
|
||||
List<ValidationError> errors) {
|
||||
if (section.containsKey(key)) {
|
||||
Object value = section.get(key);
|
||||
try {
|
||||
int intValue = toInt(value);
|
||||
if (intValue <= 0) {
|
||||
errors.add(new ValidationError(0, key,
|
||||
"Invalid value for '" + key + "': must be positive integer"));
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
errors.add(new ValidationError(0, key,
|
||||
"Invalid value for '" + key + "': must be positive integer"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateNonNegativeInteger(Map<String, Object> section, String key,
|
||||
List<ValidationError> errors) {
|
||||
if (section.containsKey(key)) {
|
||||
Object value = section.get(key);
|
||||
try {
|
||||
int intValue = toInt(value);
|
||||
if (intValue < 0) {
|
||||
errors.add(new ValidationError(0, key,
|
||||
"Invalid value for '" + key + "': must be non-negative integer"));
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
errors.add(new ValidationError(0, key,
|
||||
"Invalid value for '" + key + "': must be non-negative integer"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void validateBoolean(Map<String, Object> section, String key,
|
||||
List<ValidationError> errors) {
|
||||
if (section.containsKey(key)) {
|
||||
Object value = section.get(key);
|
||||
if (!(value instanceof Boolean)) {
|
||||
String strValue = value.toString().toLowerCase();
|
||||
if (!strValue.equals("true") && !strValue.equals("false")) {
|
||||
errors.add(new ValidationError(0, key,
|
||||
"Invalid value for '" + key + "': must be true or false"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private int toInt(Object value) {
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
return Integer.parseInt(value.toString());
|
||||
}
|
||||
|
||||
private double toDouble(Object value) {
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).doubleValue();
|
||||
}
|
||||
return Double.parseDouble(value.toString());
|
||||
}
|
||||
|
||||
private void outputHumanFormat(List<ValidationError> errors) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Configuration errors in ").append(configFile).append(":\n\n");
|
||||
|
||||
for (ValidationError error : errors) {
|
||||
sb.append(" ");
|
||||
if (error.key != null) {
|
||||
sb.append("Key '").append(error.key).append("': ");
|
||||
}
|
||||
sb.append(error.message).append("\n");
|
||||
}
|
||||
|
||||
getOut().println(sb.toString().trim());
|
||||
}
|
||||
|
||||
private Map<String, Object> toMap(List<ValidationError> errors) {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("valid", false);
|
||||
map.put("file", configFile.toString());
|
||||
|
||||
List<Map<String, Object>> errorList = new ArrayList<>();
|
||||
for (ValidationError error : errors) {
|
||||
Map<String, Object> errorMap = new LinkedHashMap<>();
|
||||
if (error.key != null) {
|
||||
errorMap.put("key", error.key);
|
||||
}
|
||||
errorMap.put("message", error.message);
|
||||
errorList.add(errorMap);
|
||||
}
|
||||
map.put("errors", errorList);
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a validation error.
|
||||
*/
|
||||
record ValidationError(int line, String key, String message) { }
|
||||
}
|
||||
@@ -1,26 +1,349 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.ipc.IpcClient;
|
||||
import com.samsonmedia.barn.ipc.IpcException;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobManifest;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Model.CommandSpec;
|
||||
import picocli.CommandLine.Spec;
|
||||
import picocli.CommandLine.Option;
|
||||
import picocli.CommandLine.Parameters;
|
||||
|
||||
/**
|
||||
* Command to show detailed information about a specific job.
|
||||
*
|
||||
* <p>Placeholder implementation - full implementation in ticket #11.
|
||||
*/
|
||||
@Command(
|
||||
name = "describe",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Show detailed job information"
|
||||
)
|
||||
public class DescribeCommand implements Runnable {
|
||||
public class DescribeCommand extends BaseCommand {
|
||||
|
||||
@Spec
|
||||
private CommandSpec spec;
|
||||
private static final Logger LOG = LoggerFactory.getLogger(DescribeCommand.class);
|
||||
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd HH:mm:ss")
|
||||
.withZone(ZoneId.systemDefault());
|
||||
private static final int DEFAULT_LOG_LINES = 20;
|
||||
|
||||
@Parameters(index = "0", description = "Job ID")
|
||||
private String jobId;
|
||||
|
||||
@Option(names = {"--logs"}, description = "Include log file contents")
|
||||
private boolean includeLogs;
|
||||
|
||||
@Option(names = {"--manifest"}, description = "Show full manifest")
|
||||
private boolean showManifest;
|
||||
|
||||
// For testing
|
||||
private Path barnDir;
|
||||
|
||||
/**
|
||||
* Sets the barn directory (for testing).
|
||||
*
|
||||
* @param barnDir the barn directory path
|
||||
*/
|
||||
public void setBarnDir(Path barnDir) {
|
||||
this.barnDir = barnDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
spec.commandLine().getOut().println("Describe command not yet implemented");
|
||||
public Integer call() {
|
||||
if (isOffline()) {
|
||||
return runOffline();
|
||||
}
|
||||
return runWithService();
|
||||
}
|
||||
|
||||
private int runOffline() {
|
||||
try {
|
||||
BarnDirectories dirs = getBarnDirectories();
|
||||
JobRepository repository = new JobRepository(dirs);
|
||||
|
||||
Optional<Job> jobOpt = repository.findById(jobId);
|
||||
if (jobOpt.isEmpty()) {
|
||||
outputError("Job not found: " + jobId);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
Job job = jobOpt.get();
|
||||
JobManifest manifest = showManifest ? repository.loadManifest(jobId) : null;
|
||||
|
||||
outputJobDetails(job, manifest, dirs);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to describe job", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int runWithService() {
|
||||
try (IpcClient client = new IpcClient(getBarnDirectories().getSocketPath())) {
|
||||
// Build request payload
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("jobId", jobId);
|
||||
payload.put("includeLogs", includeLogs);
|
||||
payload.put("includeManifest", showManifest);
|
||||
|
||||
// Send request and get response
|
||||
Object response = client.send("get_job", payload, Object.class);
|
||||
|
||||
// Convert response to Job
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
Job job = mapper.convertValue(response, Job.class);
|
||||
|
||||
// For IPC mode, we use default dirs for path display
|
||||
BarnDirectories dirs = getBarnDirectories();
|
||||
outputJobDetails(job, null, dirs);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IpcException e) {
|
||||
if ("SERVICE_NOT_RUNNING".equals(e.getCode())) {
|
||||
outputError("Service not running. Start with: barn service start\n"
|
||||
+ "Or use --offline to run without the service.");
|
||||
} else if ("NOT_FOUND".equals(e.getCode())) {
|
||||
outputError("Job not found: " + jobId);
|
||||
} else {
|
||||
outputError("IPC error: " + e.getMessage());
|
||||
}
|
||||
return EXIT_ERROR;
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to describe job", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private BarnDirectories getBarnDirectories() {
|
||||
if (barnDir != null) {
|
||||
return new BarnDirectories(barnDir);
|
||||
}
|
||||
Path defaultDir = ConfigDefaults.getDefaultBaseDir();
|
||||
return new BarnDirectories(defaultDir);
|
||||
}
|
||||
|
||||
private void outputJobDetails(Job job, JobManifest manifest, BarnDirectories dirs) throws IOException {
|
||||
OutputFormat format = globalOptions != null
|
||||
? globalOptions.getOutputFormat()
|
||||
: OutputFormat.HUMAN;
|
||||
|
||||
switch (format) {
|
||||
case HUMAN -> outputHumanFormat(job, manifest, dirs);
|
||||
case JSON -> outputJsonFormat(job, manifest, dirs);
|
||||
case XML -> outputXmlFormat(job, manifest, dirs);
|
||||
default -> outputHumanFormat(job, manifest, dirs);
|
||||
}
|
||||
}
|
||||
|
||||
private void outputHumanFormat(Job job, JobManifest manifest, BarnDirectories dirs) throws IOException {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
// Header
|
||||
sb.append("Job: ").append(job.id()).append("\n");
|
||||
sb.append("================================================================================\n");
|
||||
|
||||
// Basic info
|
||||
sb.append("State: ").append(job.state().toString().toLowerCase()).append("\n");
|
||||
if (job.tag() != null) {
|
||||
sb.append("Tag: ").append(job.tag()).append("\n");
|
||||
}
|
||||
sb.append("Command: ").append(String.join(" ", job.command())).append("\n");
|
||||
|
||||
// Timestamps
|
||||
sb.append("\nTimestamps:\n");
|
||||
sb.append(" Created: ").append(formatTimestamp(job.createdAt())).append("\n");
|
||||
sb.append(" Started: ").append(formatTimestamp(job.startedAt())).append("\n");
|
||||
sb.append(" Finished: ").append(formatTimestamp(job.finishedAt())).append("\n");
|
||||
|
||||
// Execution
|
||||
sb.append("\nExecution:\n");
|
||||
sb.append(" PID: ").append(job.pid() != null ? job.pid() : "-").append("\n");
|
||||
sb.append(" Exit Code: ").append(job.exitCode() != null ? job.exitCode() : "-").append("\n");
|
||||
if (job.heartbeat() != null) {
|
||||
sb.append(" Heartbeat: ").append(formatTimestamp(job.heartbeat()));
|
||||
sb.append(" (").append(relativeTime(job.heartbeat())).append(")\n");
|
||||
}
|
||||
if (job.error() != null) {
|
||||
sb.append(" Error: ").append(job.error()).append("\n");
|
||||
}
|
||||
|
||||
// Retry info
|
||||
if (job.retryCount() > 0 || job.retryAt() != null) {
|
||||
sb.append("\nRetry:\n");
|
||||
sb.append(" Attempts: ").append(job.retryCount()).append("\n");
|
||||
if (job.retryAt() != null) {
|
||||
sb.append(" Next Retry: ").append(formatTimestamp(job.retryAt())).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
// Paths
|
||||
sb.append("\nFiles:\n");
|
||||
sb.append(" Work Dir: ").append(dirs.getJobWorkDir(job.id())).append("\n");
|
||||
sb.append(" Logs Dir: ").append(dirs.getJobLogsDir(job.id())).append("\n");
|
||||
|
||||
// Manifest
|
||||
if (manifest != null) {
|
||||
sb.append("\nManifest:\n");
|
||||
sb.append(" Max Retries: ").append(manifest.maxRetries()).append("\n");
|
||||
sb.append(" Retry Delay: ").append(manifest.retryDelaySeconds()).append("s\n");
|
||||
sb.append(" Backoff: ").append(manifest.retryBackoffMultiplier()).append("x\n");
|
||||
}
|
||||
|
||||
// Logs
|
||||
if (includeLogs) {
|
||||
appendLogs(sb, dirs.getJobLogsDir(job.id()));
|
||||
}
|
||||
|
||||
getOut().println(sb.toString().trim());
|
||||
}
|
||||
|
||||
private void outputJsonFormat(Job job, JobManifest manifest, BarnDirectories dirs) throws IOException {
|
||||
Map<String, Object> response = buildResponseMap(job, manifest, dirs);
|
||||
output(response);
|
||||
}
|
||||
|
||||
private void outputXmlFormat(Job job, JobManifest manifest, BarnDirectories dirs) throws IOException {
|
||||
Map<String, Object> response = buildResponseMap(job, manifest, dirs);
|
||||
output(response);
|
||||
}
|
||||
|
||||
private Map<String, Object> buildResponseMap(Job job, JobManifest manifest, BarnDirectories dirs)
|
||||
throws IOException {
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
|
||||
// Job details
|
||||
response.put("id", job.id());
|
||||
response.put("state", job.state().toString().toLowerCase());
|
||||
response.put("tag", job.tag());
|
||||
response.put("command", job.command());
|
||||
response.put("createdAt", job.createdAt());
|
||||
response.put("startedAt", job.startedAt());
|
||||
response.put("finishedAt", job.finishedAt());
|
||||
response.put("pid", job.pid());
|
||||
response.put("exitCode", job.exitCode());
|
||||
response.put("error", job.error());
|
||||
response.put("heartbeat", job.heartbeat());
|
||||
response.put("retryCount", job.retryCount());
|
||||
response.put("retryAt", job.retryAt());
|
||||
|
||||
// Paths
|
||||
Map<String, String> paths = new LinkedHashMap<>();
|
||||
paths.put("jobDir", dirs.getJobDir(job.id()).toString());
|
||||
paths.put("workDir", dirs.getJobWorkDir(job.id()).toString());
|
||||
paths.put("logsDir", dirs.getJobLogsDir(job.id()).toString());
|
||||
response.put("paths", paths);
|
||||
|
||||
// Manifest
|
||||
if (manifest != null) {
|
||||
Map<String, Object> manifestMap = new LinkedHashMap<>();
|
||||
manifestMap.put("maxRetries", manifest.maxRetries());
|
||||
manifestMap.put("retryDelaySeconds", manifest.retryDelaySeconds());
|
||||
manifestMap.put("retryBackoffMultiplier", manifest.retryBackoffMultiplier());
|
||||
response.put("manifest", manifestMap);
|
||||
}
|
||||
|
||||
// Logs
|
||||
if (includeLogs) {
|
||||
Map<String, String> logs = new LinkedHashMap<>();
|
||||
Path logsDir = dirs.getJobLogsDir(job.id());
|
||||
logs.put("stdout", readLogFile(logsDir.resolve("stdout.log")));
|
||||
logs.put("stderr", readLogFile(logsDir.resolve("stderr.log")));
|
||||
response.put("logs", logs);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private void appendLogs(StringBuilder sb, Path logsDir) throws IOException {
|
||||
appendLogFile(sb, logsDir.resolve("stdout.log"), "stdout.log");
|
||||
appendLogFile(sb, logsDir.resolve("stderr.log"), "stderr.log");
|
||||
}
|
||||
|
||||
private void appendLogFile(StringBuilder sb, Path logFile, String name) throws IOException {
|
||||
if (!Files.exists(logFile)) {
|
||||
return;
|
||||
}
|
||||
|
||||
List<String> lines = tailFile(logFile, DEFAULT_LOG_LINES);
|
||||
if (lines.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
sb.append("\n--- ").append(name).append(" (last ").append(lines.size()).append(" lines) ---\n");
|
||||
for (String line : lines) {
|
||||
sb.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
private String readLogFile(Path logFile) throws IOException {
|
||||
if (!Files.exists(logFile)) {
|
||||
return "";
|
||||
}
|
||||
|
||||
List<String> lines = tailFile(logFile, DEFAULT_LOG_LINES);
|
||||
return String.join("\n", lines);
|
||||
}
|
||||
|
||||
private List<String> tailFile(Path file, int maxLines) throws IOException {
|
||||
try (Stream<String> stream = Files.lines(file)) {
|
||||
List<String> allLines = stream.collect(Collectors.toList());
|
||||
int start = Math.max(0, allLines.size() - maxLines);
|
||||
return allLines.subList(start, allLines.size());
|
||||
}
|
||||
}
|
||||
|
||||
private String formatTimestamp(Instant timestamp) {
|
||||
if (timestamp == null) {
|
||||
return "-";
|
||||
}
|
||||
return DATE_FORMAT.format(timestamp);
|
||||
}
|
||||
|
||||
private String relativeTime(Instant instant) {
|
||||
if (instant == null) {
|
||||
return "";
|
||||
}
|
||||
Duration elapsed = Duration.between(instant, Instant.now());
|
||||
long seconds = elapsed.getSeconds();
|
||||
|
||||
if (seconds < 0) {
|
||||
return "in the future";
|
||||
}
|
||||
if (seconds < 60) {
|
||||
return seconds + "s ago";
|
||||
}
|
||||
if (seconds < 3600) {
|
||||
return (seconds / 60) + "m ago";
|
||||
}
|
||||
if (seconds < 86400) {
|
||||
return (seconds / 3600) + "h ago";
|
||||
}
|
||||
return (seconds / 86400) + "d ago";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Global options shared by all CLI commands.
|
||||
*
|
||||
* <p>This class is used as a picocli mixin to provide common options
|
||||
* like output format, config file path, and offline mode.
|
||||
*/
|
||||
public class GlobalOptions {
|
||||
|
||||
@Option(
|
||||
names = {"-o", "--output"},
|
||||
description = "Output format: human, json, xml",
|
||||
defaultValue = "HUMAN"
|
||||
)
|
||||
private OutputFormat outputFormat = OutputFormat.HUMAN;
|
||||
|
||||
@Option(
|
||||
names = {"--config"},
|
||||
description = "Path to config file"
|
||||
)
|
||||
private Path configPath;
|
||||
|
||||
@Option(
|
||||
names = {"--offline"},
|
||||
description = "Run without service connection (for testing)"
|
||||
)
|
||||
private boolean offline;
|
||||
|
||||
/**
|
||||
* Gets the output format.
|
||||
*
|
||||
* @return the output format
|
||||
*/
|
||||
public OutputFormat getOutputFormat() {
|
||||
return outputFormat;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the optional config file path.
|
||||
*
|
||||
* @return the config path if specified, or empty
|
||||
*/
|
||||
public Optional<Path> getConfigPath() {
|
||||
return Optional.ofNullable(configPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if offline mode is enabled.
|
||||
*
|
||||
* @return true if running in offline mode
|
||||
*/
|
||||
public boolean isOffline() {
|
||||
return offline;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Formats output in a human-readable table format.
|
||||
*
|
||||
* <p>Produces nicely aligned tables with optional ANSI color codes
|
||||
* when running in an interactive terminal.
|
||||
*/
|
||||
public class HumanFormatter implements OutputFormatter {
|
||||
|
||||
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd HH:mm:ss")
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
// ANSI color codes
|
||||
private static final String RESET = "\u001B[0m";
|
||||
private static final String GREEN = "\u001B[32m";
|
||||
private static final String RED = "\u001B[31m";
|
||||
private static final String YELLOW = "\u001B[33m";
|
||||
private static final String CYAN = "\u001B[36m";
|
||||
private static final String BOLD = "\u001B[1m";
|
||||
|
||||
private final boolean useColors;
|
||||
|
||||
/**
|
||||
* Creates a HumanFormatter with automatic color detection.
|
||||
*/
|
||||
public HumanFormatter() {
|
||||
this(System.console() != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a HumanFormatter with explicit color setting.
|
||||
*
|
||||
* @param useColors true to use ANSI colors
|
||||
*/
|
||||
public HumanFormatter(boolean useColors) {
|
||||
this.useColors = useColors;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String format(Object value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (value instanceof Job job) {
|
||||
return formatJob(job);
|
||||
}
|
||||
|
||||
if (value instanceof Map<?, ?> map) {
|
||||
return formatMap(map);
|
||||
}
|
||||
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String formatList(List<?> values) {
|
||||
if (values == null || values.isEmpty()) {
|
||||
return "No results found.";
|
||||
}
|
||||
|
||||
// Check if all values are jobs
|
||||
if (values.stream().allMatch(v -> v instanceof Job)) {
|
||||
return formatJobTable(values.stream().map(v -> (Job) v).toList());
|
||||
}
|
||||
|
||||
// Generic list formatting
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object value : values) {
|
||||
sb.append(format(value)).append("\n");
|
||||
}
|
||||
return sb.toString().trim();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String formatError(String message, Throwable cause) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(colorize("Error: ", RED, BOLD)).append(message);
|
||||
|
||||
if (cause != null) {
|
||||
sb.append("\n");
|
||||
sb.append(colorize("Cause: ", YELLOW)).append(cause.getMessage());
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String formatJob(Job job) {
|
||||
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(" Command: ").append(String.join(" ", job.command())).append("\n");
|
||||
|
||||
if (job.tag() != null) {
|
||||
sb.append(" Tag: ").append(job.tag()).append("\n");
|
||||
}
|
||||
|
||||
sb.append(" Created: ").append(formatTimestamp(job.createdAt())).append("\n");
|
||||
|
||||
if (job.startedAt() != null) {
|
||||
sb.append(" Started: ").append(formatTimestamp(job.startedAt())).append("\n");
|
||||
}
|
||||
|
||||
if (job.finishedAt() != null) {
|
||||
sb.append(" Finished: ").append(formatTimestamp(job.finishedAt())).append("\n");
|
||||
}
|
||||
|
||||
if (job.exitCode() != null) {
|
||||
sb.append(" Exit: ").append(colorizeExitCode(job.exitCode())).append("\n");
|
||||
}
|
||||
|
||||
if (job.error() != null) {
|
||||
sb.append(" Error: ").append(colorize(job.error(), RED)).append("\n");
|
||||
}
|
||||
|
||||
if (job.pid() != null) {
|
||||
sb.append(" PID: ").append(job.pid()).append("\n");
|
||||
}
|
||||
|
||||
if (job.retryCount() > 0) {
|
||||
sb.append(" Retries: ").append(job.retryCount()).append("\n");
|
||||
}
|
||||
|
||||
return sb.toString().trim();
|
||||
}
|
||||
|
||||
private String formatJobTable(List<Job> jobs) {
|
||||
// Define columns
|
||||
List<String> headers = List.of("ID", "STATE", "TAG", "CREATED", "EXIT");
|
||||
|
||||
// Convert jobs to rows
|
||||
List<List<String>> rows = new ArrayList<>();
|
||||
for (Job job : jobs) {
|
||||
rows.add(List.of(
|
||||
job.id(),
|
||||
job.state().toString().toLowerCase(),
|
||||
job.tag() != null ? job.tag() : "-",
|
||||
formatTimestamp(job.createdAt()),
|
||||
job.exitCode() != null ? job.exitCode().toString() : "-"
|
||||
));
|
||||
}
|
||||
|
||||
return formatTable(headers, rows, jobs);
|
||||
}
|
||||
|
||||
private String formatTable(List<String> headers, List<List<String>> rows, List<Job> jobs) {
|
||||
// Calculate column widths
|
||||
int[] widths = new int[headers.size()];
|
||||
for (int i = 0; i < headers.size(); i++) {
|
||||
widths[i] = headers.get(i).length();
|
||||
}
|
||||
|
||||
for (List<String> row : rows) {
|
||||
for (int i = 0; i < row.size(); i++) {
|
||||
widths[i] = Math.max(widths[i], row.get(i).length());
|
||||
}
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
// Header row
|
||||
for (int i = 0; i < headers.size(); i++) {
|
||||
sb.append(colorize(pad(headers.get(i), widths[i]), BOLD));
|
||||
if (i < headers.size() - 1) {
|
||||
sb.append(" ");
|
||||
}
|
||||
}
|
||||
sb.append("\n");
|
||||
|
||||
// Data rows
|
||||
for (int r = 0; r < rows.size(); r++) {
|
||||
List<String> row = rows.get(r);
|
||||
Job job = jobs.get(r);
|
||||
for (int i = 0; i < row.size(); i++) {
|
||||
String cell = pad(row.get(i), widths[i]);
|
||||
|
||||
// Apply colors based on column
|
||||
if (i == 1) { // STATE column
|
||||
cell = colorizeState(job.state(), cell);
|
||||
} else if (i == 4 && !cell.trim().equals("-")) { // EXIT column
|
||||
cell = colorizeExitCode(job.exitCode(), cell);
|
||||
}
|
||||
|
||||
sb.append(cell);
|
||||
if (i < row.size() - 1) {
|
||||
sb.append(" ");
|
||||
}
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
|
||||
return sb.toString().trim();
|
||||
}
|
||||
|
||||
private String formatMap(Map<?, ?> map) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int maxKeyLength = 0;
|
||||
|
||||
for (Object key : map.keySet()) {
|
||||
maxKeyLength = Math.max(maxKeyLength, key.toString().length());
|
||||
}
|
||||
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
String key = entry.getKey().toString();
|
||||
sb.append(colorize(pad(key + ":", maxKeyLength + 1), BOLD));
|
||||
sb.append(" ").append(entry.getValue()).append("\n");
|
||||
}
|
||||
|
||||
return sb.toString().trim();
|
||||
}
|
||||
|
||||
private String formatTimestamp(Instant timestamp) {
|
||||
if (timestamp == null) {
|
||||
return "-";
|
||||
}
|
||||
return DATE_FORMAT.format(timestamp);
|
||||
}
|
||||
|
||||
private String colorizeState(JobState state) {
|
||||
return colorizeState(state, state.toString().toLowerCase());
|
||||
}
|
||||
|
||||
private String colorizeState(JobState state, String text) {
|
||||
return switch (state) {
|
||||
case QUEUED -> colorize(text, CYAN);
|
||||
case RUNNING -> colorize(text, YELLOW);
|
||||
case SUCCEEDED -> colorize(text, GREEN);
|
||||
case FAILED -> colorize(text, RED);
|
||||
case CANCELED -> text;
|
||||
};
|
||||
}
|
||||
|
||||
private String colorizeExitCode(Integer exitCode) {
|
||||
return colorizeExitCode(exitCode, String.valueOf(exitCode));
|
||||
}
|
||||
|
||||
private String colorizeExitCode(Integer exitCode, String text) {
|
||||
if (exitCode == null) {
|
||||
return text;
|
||||
}
|
||||
return exitCode == 0 ? colorize(text, GREEN) : colorize(text, RED);
|
||||
}
|
||||
|
||||
private String colorize(String text, String... codes) {
|
||||
if (!useColors || codes.length == 0) {
|
||||
return text;
|
||||
}
|
||||
return String.join("", codes) + text + RESET;
|
||||
}
|
||||
|
||||
private String pad(String text, int width) {
|
||||
if (text.length() >= width) {
|
||||
return text;
|
||||
}
|
||||
return text + " ".repeat(width - text.length());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
/**
|
||||
* Formats output as JSON.
|
||||
*
|
||||
* <p>Produces machine-readable JSON with proper ISO-8601 date formatting.
|
||||
*/
|
||||
public class JsonFormatter implements OutputFormatter {
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
/**
|
||||
* Creates a JsonFormatter with default settings.
|
||||
*/
|
||||
public JsonFormatter() {
|
||||
this.mapper = createObjectMapper();
|
||||
}
|
||||
|
||||
private static ObjectMapper createObjectMapper() {
|
||||
ObjectMapper om = new ObjectMapper();
|
||||
om.registerModule(new JavaTimeModule());
|
||||
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
om.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
return om;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String format(Object value) {
|
||||
if (value == null) {
|
||||
return "null";
|
||||
}
|
||||
|
||||
try {
|
||||
return mapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
return formatError("Failed to serialize object", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String formatList(List<?> values) {
|
||||
if (values == null) {
|
||||
return "[]";
|
||||
}
|
||||
|
||||
try {
|
||||
return mapper.writeValueAsString(values);
|
||||
} catch (JsonProcessingException e) {
|
||||
return formatError("Failed to serialize list", e);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String formatError(String message, Throwable cause) {
|
||||
Map<String, Object> error = new LinkedHashMap<>();
|
||||
error.put("error", true);
|
||||
error.put("message", message);
|
||||
|
||||
if (cause != null) {
|
||||
error.put("cause", cause.getMessage());
|
||||
error.put("type", cause.getClass().getSimpleName());
|
||||
}
|
||||
|
||||
try {
|
||||
return mapper.writeValueAsString(error);
|
||||
} catch (JsonProcessingException e) {
|
||||
// Fallback to plain JSON if serialization fails
|
||||
return "{\"error\":true,\"message\":\"" + escapeJson(message) + "\"}";
|
||||
}
|
||||
}
|
||||
|
||||
private String escapeJson(String text) {
|
||||
if (text == null) {
|
||||
return "";
|
||||
}
|
||||
return text
|
||||
.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\t", "\\t");
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,198 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.execution.ProcessUtils;
|
||||
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.state.BarnDirectories;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Model.CommandSpec;
|
||||
import picocli.CommandLine.Spec;
|
||||
import picocli.CommandLine.Option;
|
||||
import picocli.CommandLine.Parameters;
|
||||
|
||||
/**
|
||||
* Command to stop a running job.
|
||||
*
|
||||
* <p>Placeholder implementation - full implementation in ticket #12.
|
||||
*/
|
||||
@Command(
|
||||
name = "kill",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Stop a running job"
|
||||
)
|
||||
public class KillCommand implements Runnable {
|
||||
public class KillCommand extends BaseCommand {
|
||||
|
||||
@Spec
|
||||
private CommandSpec spec;
|
||||
private static final Logger LOG = LoggerFactory.getLogger(KillCommand.class);
|
||||
|
||||
@Parameters(index = "0", description = "Job ID")
|
||||
private String jobId;
|
||||
|
||||
@Option(names = {"--force", "-f"}, description = "Force kill (SIGKILL)")
|
||||
private boolean force;
|
||||
|
||||
@Option(names = {"--quiet", "-q"}, description = "No output on success")
|
||||
private boolean quiet;
|
||||
|
||||
// For testing
|
||||
private Path barnDir;
|
||||
|
||||
/**
|
||||
* Sets the barn directory (for testing).
|
||||
*
|
||||
* @param barnDir the barn directory path
|
||||
*/
|
||||
public void setBarnDir(Path barnDir) {
|
||||
this.barnDir = barnDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
spec.commandLine().getOut().println("Kill command not yet implemented");
|
||||
public Integer call() {
|
||||
if (isOffline()) {
|
||||
return runOffline();
|
||||
}
|
||||
return runWithService();
|
||||
}
|
||||
|
||||
private int runOffline() {
|
||||
try {
|
||||
BarnDirectories dirs = getBarnDirectories();
|
||||
JobRepository repository = new JobRepository(dirs);
|
||||
|
||||
Optional<Job> jobOpt = repository.findById(jobId);
|
||||
if (jobOpt.isEmpty()) {
|
||||
outputError("Job not found: " + jobId);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
Job job = jobOpt.get();
|
||||
if (job.state() != JobState.RUNNING) {
|
||||
outputError("Job is not running (state: " + job.state().toLowercase() + ")");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
// Kill the process if it has a PID
|
||||
if (job.pid() != null) {
|
||||
boolean killed;
|
||||
if (force) {
|
||||
killed = ProcessUtils.killTreeForcibly(job.pid());
|
||||
} else {
|
||||
killed = ProcessUtils.killTree(job.pid());
|
||||
}
|
||||
LOG.debug("Kill result for PID {}: {}", job.pid(), killed);
|
||||
}
|
||||
|
||||
// Mark job as canceled
|
||||
repository.markCanceled(jobId);
|
||||
|
||||
// Output result
|
||||
if (!quiet) {
|
||||
outputKillResult(job);
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to kill job", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int runWithService() {
|
||||
try (IpcClient client = new IpcClient(getBarnDirectories().getSocketPath())) {
|
||||
// Build request payload
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("jobId", jobId);
|
||||
payload.put("force", force);
|
||||
|
||||
// Send request and get response
|
||||
Object response = client.send("kill_job", payload, Object.class);
|
||||
|
||||
// Convert response to Job
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
Job job = mapper.convertValue(response, Job.class);
|
||||
|
||||
// Output result
|
||||
if (!quiet) {
|
||||
outputKillResult(job);
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IpcException e) {
|
||||
if ("SERVICE_NOT_RUNNING".equals(e.getCode())) {
|
||||
outputError("Service not running. Start with: barn service start\n"
|
||||
+ "Or use --offline to run without the service.");
|
||||
} else if ("NOT_FOUND".equals(e.getCode())) {
|
||||
outputError("Job not found: " + jobId);
|
||||
} else if ("INVALID_STATE".equals(e.getCode())) {
|
||||
outputError(e.getMessage());
|
||||
} else {
|
||||
outputError("IPC error: " + e.getMessage());
|
||||
}
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private BarnDirectories getBarnDirectories() {
|
||||
if (barnDir != null) {
|
||||
return new BarnDirectories(barnDir);
|
||||
}
|
||||
Path defaultDir = ConfigDefaults.getDefaultBaseDir();
|
||||
return new BarnDirectories(defaultDir);
|
||||
}
|
||||
|
||||
private void outputKillResult(Job job) {
|
||||
OutputFormat format = globalOptions != null
|
||||
? globalOptions.getOutputFormat()
|
||||
: OutputFormat.HUMAN;
|
||||
|
||||
switch (format) {
|
||||
case HUMAN -> outputHumanFormat(job);
|
||||
case JSON -> outputJsonFormat(job);
|
||||
case XML -> outputXmlFormat(job);
|
||||
default -> outputHumanFormat(job);
|
||||
}
|
||||
}
|
||||
|
||||
private void outputHumanFormat(Job job) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Job ").append(job.id()).append(" killed\n");
|
||||
sb.append(" Previous state: ").append(job.state().toLowercase()).append("\n");
|
||||
sb.append(" New state: canceled");
|
||||
getOut().println(sb.toString());
|
||||
}
|
||||
|
||||
private void outputJsonFormat(Job job) {
|
||||
Map<String, Object> response = buildResponseMap(job);
|
||||
output(response);
|
||||
}
|
||||
|
||||
private void outputXmlFormat(Job job) {
|
||||
Map<String, Object> response = buildResponseMap(job);
|
||||
output(response);
|
||||
}
|
||||
|
||||
private Map<String, Object> buildResponseMap(Job job) {
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
response.put("id", job.id());
|
||||
response.put("previousState", job.state().toLowercase());
|
||||
response.put("newState", "canceled");
|
||||
response.put("message", "Job was killed");
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
/**
|
||||
* Output format options for CLI commands.
|
||||
*/
|
||||
public enum OutputFormat {
|
||||
/** Human-readable formatted output (default). */
|
||||
HUMAN,
|
||||
|
||||
/** Machine-readable JSON output. */
|
||||
JSON,
|
||||
|
||||
/** Machine-readable XML output. */
|
||||
XML
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Interface for formatting CLI output in different formats.
|
||||
*
|
||||
* <p>Implementations provide format-specific rendering of command output
|
||||
* including jobs, lists, and error messages.
|
||||
*/
|
||||
public interface OutputFormatter {
|
||||
|
||||
/**
|
||||
* Formats a single object for output.
|
||||
*
|
||||
* @param value the object to format
|
||||
* @return the formatted string
|
||||
*/
|
||||
String format(Object value);
|
||||
|
||||
/**
|
||||
* Formats a list of objects for output.
|
||||
*
|
||||
* @param values the list of values to format
|
||||
* @return the formatted string
|
||||
*/
|
||||
String formatList(List<?> values);
|
||||
|
||||
/**
|
||||
* Formats an error message.
|
||||
*
|
||||
* @param message the error message
|
||||
* @param cause the optional cause (may be null)
|
||||
* @return the formatted error string
|
||||
*/
|
||||
String formatError(String message, Throwable cause);
|
||||
|
||||
/**
|
||||
* Creates a formatter for the specified output format.
|
||||
*
|
||||
* @param format the output format
|
||||
* @return the appropriate formatter instance
|
||||
*/
|
||||
static OutputFormatter forFormat(OutputFormat format) {
|
||||
return switch (format) {
|
||||
case HUMAN -> new HumanFormatter();
|
||||
case JSON -> new JsonFormatter();
|
||||
case XML -> new XmlFormatter();
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,197 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
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.state.BarnDirectories;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Model.CommandSpec;
|
||||
import picocli.CommandLine.Spec;
|
||||
import picocli.CommandLine.Option;
|
||||
import picocli.CommandLine.Parameters;
|
||||
|
||||
/**
|
||||
* Command to start a new job.
|
||||
*
|
||||
* <p>Placeholder implementation - full implementation in ticket #9.
|
||||
* <p>Creates a job with the specified command and queues it for execution.
|
||||
* In offline mode, the job is executed directly without the service.
|
||||
*/
|
||||
@Command(
|
||||
name = "run",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Start a new job"
|
||||
)
|
||||
public class RunCommand implements Runnable {
|
||||
public class RunCommand extends BaseCommand {
|
||||
|
||||
@Spec
|
||||
private CommandSpec spec;
|
||||
private static final Logger LOG = LoggerFactory.getLogger(RunCommand.class);
|
||||
|
||||
@Option(names = {"--tag", "-t"}, description = "Tag for filtering jobs")
|
||||
private String tag;
|
||||
|
||||
@Option(names = {"--max-retries"}, description = "Override max retries")
|
||||
private Integer maxRetries;
|
||||
|
||||
@Option(names = {"--retry-delay"}, description = "Override retry delay (seconds)")
|
||||
private Integer retryDelay;
|
||||
|
||||
@Option(names = {"--timeout"}, description = "Job timeout (seconds)")
|
||||
private Integer timeout;
|
||||
|
||||
@Parameters(description = "Command to run", arity = "1..*")
|
||||
private List<String> command;
|
||||
|
||||
// For testing - allows overriding the barn directory
|
||||
private Path barnDir;
|
||||
|
||||
/**
|
||||
* Sets the barn directory (for testing).
|
||||
*
|
||||
* @param barnDir the barn directory path
|
||||
*/
|
||||
public void setBarnDir(Path barnDir) {
|
||||
this.barnDir = barnDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
spec.commandLine().getOut().println("Run command not yet implemented");
|
||||
public Integer call() {
|
||||
if (command == null || command.isEmpty()) {
|
||||
outputError("No command specified");
|
||||
return EXIT_USAGE;
|
||||
}
|
||||
|
||||
if (isOffline()) {
|
||||
return runOffline();
|
||||
}
|
||||
|
||||
return runWithService();
|
||||
}
|
||||
|
||||
private int runOffline() {
|
||||
try {
|
||||
BarnDirectories dirs = getBarnDirectories();
|
||||
dirs.initialize();
|
||||
|
||||
JobRepository repository = new JobRepository(dirs);
|
||||
JobsConfig jobsConfig = buildJobsConfig();
|
||||
|
||||
// Create the job
|
||||
Job job = repository.create(command, tag, jobsConfig);
|
||||
|
||||
LOG.info("Created job {} in offline mode", job.id());
|
||||
|
||||
// Output job info in the appropriate format
|
||||
outputJobCreated(job);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to create job", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int runWithService() {
|
||||
try (IpcClient client = new IpcClient(getBarnDirectories().getSocketPath())) {
|
||||
// Build request payload
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("command", command);
|
||||
if (tag != null) {
|
||||
payload.put("tag", tag);
|
||||
}
|
||||
if (maxRetries != null) {
|
||||
payload.put("maxRetries", maxRetries);
|
||||
}
|
||||
if (retryDelay != null) {
|
||||
payload.put("retryDelaySeconds", retryDelay);
|
||||
}
|
||||
|
||||
// Send request and get response
|
||||
Object response = client.send("run_job", payload, Object.class);
|
||||
|
||||
// Convert response to Job
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
Job job = mapper.convertValue(response, Job.class);
|
||||
|
||||
LOG.info("Created job {} via service", job.id());
|
||||
|
||||
// Output job info
|
||||
outputJobCreated(job);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IpcException e) {
|
||||
if ("SERVICE_NOT_RUNNING".equals(e.getCode())) {
|
||||
outputError("Service not running. Start with: barn service start\n"
|
||||
+ "Or use --offline to run without the service.");
|
||||
} else {
|
||||
outputError("IPC error: " + e.getMessage());
|
||||
}
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private BarnDirectories getBarnDirectories() {
|
||||
if (barnDir != null) {
|
||||
return new BarnDirectories(barnDir);
|
||||
}
|
||||
// Use default barn directories in system temp
|
||||
Path defaultDir = ConfigDefaults.getDefaultBaseDir();
|
||||
return new BarnDirectories(defaultDir);
|
||||
}
|
||||
|
||||
private JobsConfig buildJobsConfig() {
|
||||
JobsConfig defaults = JobsConfig.withDefaults();
|
||||
|
||||
// Override with command-line options if provided
|
||||
int actualMaxRetries = maxRetries != null ? maxRetries : defaults.maxRetries();
|
||||
int actualRetryDelay = retryDelay != null ? retryDelay : defaults.retryDelaySeconds();
|
||||
int actualTimeout = timeout != null ? timeout : defaults.defaultTimeoutSeconds();
|
||||
|
||||
return new JobsConfig(
|
||||
actualTimeout,
|
||||
actualMaxRetries,
|
||||
actualRetryDelay,
|
||||
defaults.retryBackoffMultiplier(),
|
||||
defaults.retryOnExitCodes()
|
||||
);
|
||||
}
|
||||
|
||||
private void outputJobCreated(Job job) {
|
||||
OutputFormat format = globalOptions != null
|
||||
? globalOptions.getOutputFormat()
|
||||
: OutputFormat.HUMAN;
|
||||
|
||||
if (format == OutputFormat.HUMAN) {
|
||||
outputHumanFormat(job);
|
||||
} else {
|
||||
// JSON and XML use the standard formatters
|
||||
output(job);
|
||||
}
|
||||
}
|
||||
|
||||
private void outputHumanFormat(Job job) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append("Job created: ").append(job.id()).append("\n");
|
||||
sb.append(" Command: ").append(String.join(" ", job.command())).append("\n");
|
||||
sb.append(" Tag: ").append(job.tag() != null ? job.tag() : "-").append("\n");
|
||||
sb.append(" State: ").append(job.state().toString().toLowerCase());
|
||||
|
||||
getOut().println(sb.toString());
|
||||
}
|
||||
}
|
||||
@@ -7,12 +7,22 @@ import picocli.CommandLine.Spec;
|
||||
/**
|
||||
* Command to manage the Barn service.
|
||||
*
|
||||
* <p>Placeholder implementation - full implementation in ticket #16.
|
||||
* <p>Provides subcommands for starting, stopping, and monitoring the service.
|
||||
*/
|
||||
@Command(
|
||||
name = "service",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Manage the Barn service"
|
||||
description = "Manage the Barn service",
|
||||
subcommands = {
|
||||
ServiceStartCommand.class,
|
||||
ServiceStopCommand.class,
|
||||
ServiceRestartCommand.class,
|
||||
ServiceReloadCommand.class,
|
||||
ServiceStatusCommand.class,
|
||||
ServiceLogsCommand.class,
|
||||
ServiceInstallCommand.class,
|
||||
ServiceUninstallCommand.class
|
||||
}
|
||||
)
|
||||
public class ServiceCommand implements Runnable {
|
||||
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.config.OperatingSystem;
|
||||
import com.samsonmedia.barn.platform.linux.SystemdManager;
|
||||
import com.samsonmedia.barn.platform.macos.LaunchdManager;
|
||||
import com.samsonmedia.barn.platform.windows.WindowsServiceManager;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to install Barn as a system service.
|
||||
*
|
||||
* <p>Supports platform-specific service installation:
|
||||
* <ul>
|
||||
* <li>macOS: launchd (LaunchDaemons/LaunchAgents)</li>
|
||||
* <li>Linux: systemd (planned)</li>
|
||||
* <li>Windows: Windows Service (planned)</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Command(
|
||||
name = "install",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Install Barn as a system service"
|
||||
)
|
||||
public class ServiceInstallCommand extends BaseCommand {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.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;
|
||||
|
||||
@Option(names = {"--binary"}, description = "Path to barn binary (auto-detected if not specified)")
|
||||
private Path binaryPath;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
OperatingSystem os = OperatingSystem.current();
|
||||
|
||||
return switch (os) {
|
||||
case MACOS -> installMacOs();
|
||||
case LINUX -> installLinux();
|
||||
case WINDOWS -> installWindows();
|
||||
};
|
||||
}
|
||||
|
||||
private int installMacOs() {
|
||||
LaunchdManager launchd = new LaunchdManager();
|
||||
|
||||
// Check if already installed
|
||||
if (launchd.isLoaded()) {
|
||||
outputError("Barn service is already installed. Use 'barn service uninstall' first.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
try {
|
||||
Path effectiveBarnDir = getEffectiveBarnDir();
|
||||
Path effectiveBinaryPath = getEffectiveBinaryPath();
|
||||
|
||||
// Ensure barn directory exists
|
||||
Files.createDirectories(effectiveBarnDir);
|
||||
Files.createDirectories(effectiveBarnDir.resolve("logs"));
|
||||
|
||||
// Generate and write plist
|
||||
String plistContent = launchd.generatePlist(effectiveBinaryPath, effectiveBarnDir);
|
||||
Path plistPath = userService ? launchd.getUserAgentPath() : 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.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
launchd.writePlist(plistPath, plistContent);
|
||||
|
||||
// Load the service
|
||||
launchd.load(plistPath);
|
||||
|
||||
String serviceType = userService ? "user agent" : "system daemon";
|
||||
getOut().println("Barn installed as macOS " + serviceType);
|
||||
getOut().println("Plist location: " + plistPath);
|
||||
getOut().println("Service will start automatically on login/boot.");
|
||||
getOut().println();
|
||||
getOut().println("To start now: barn service start");
|
||||
getOut().println("To uninstall: barn service uninstall");
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to install service", e);
|
||||
return EXIT_ERROR;
|
||||
} catch (LaunchdManager.LaunchdException e) {
|
||||
outputError("Failed to load service: " + e.getMessage());
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int installLinux() {
|
||||
if (!SystemdManager.hasSystemd()) {
|
||||
outputError("Systemd is not available on this system");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
SystemdManager systemd = new SystemdManager();
|
||||
|
||||
// Check if already installed
|
||||
Path unitPath = userService ? systemd.getUserServicePath() : systemd.getSystemServicePath();
|
||||
if (Files.exists(unitPath)) {
|
||||
outputError("Barn service is already installed. Use 'barn service uninstall' first.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
try {
|
||||
Path effectiveBarnDir = getEffectiveBarnDir();
|
||||
Path effectiveBinaryPath = getEffectiveBinaryPath();
|
||||
|
||||
// Ensure barn directory exists
|
||||
Files.createDirectories(effectiveBarnDir);
|
||||
Files.createDirectories(effectiveBarnDir.resolve("logs"));
|
||||
|
||||
// Generate and write unit file
|
||||
String unitContent = systemd.generateUnitFile(effectiveBinaryPath, effectiveBarnDir, userService);
|
||||
|
||||
// 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.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
systemd.writeUnitFile(unitPath, unitContent);
|
||||
|
||||
// Reload systemd and enable the service
|
||||
systemd.daemonReload(userService);
|
||||
systemd.enable(userService);
|
||||
|
||||
String serviceType = userService ? "user service" : "system service";
|
||||
getOut().println("Barn installed as Linux " + serviceType);
|
||||
getOut().println("Unit file: " + unitPath);
|
||||
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");
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to install service", e);
|
||||
return EXIT_ERROR;
|
||||
} catch (SystemdManager.SystemdException e) {
|
||||
outputError("Failed to configure systemd: " + e.getMessage());
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int installWindows() {
|
||||
if (!WindowsServiceManager.hasWindowsServices()) {
|
||||
outputError("Windows services are not available on this system");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
WindowsServiceManager winService = new WindowsServiceManager();
|
||||
|
||||
// Check if already installed
|
||||
if (winService.isInstalled()) {
|
||||
outputError("Barn service is already installed. Use 'barn service uninstall' first.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
// Check for admin privileges
|
||||
if (!WindowsServiceManager.isAdmin()) {
|
||||
outputError("Windows service installation requires administrator privileges. "
|
||||
+ "Please run Command Prompt as Administrator and try again.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
try {
|
||||
Path effectiveBarnDir = getEffectiveBarnDir();
|
||||
Path effectiveBinaryPath = getEffectiveBinaryPath();
|
||||
|
||||
// Ensure barn directory exists
|
||||
Files.createDirectories(effectiveBarnDir);
|
||||
Files.createDirectories(effectiveBarnDir.resolve("logs"));
|
||||
|
||||
// Install the service
|
||||
winService.install(effectiveBinaryPath.toString(), effectiveBarnDir.toString());
|
||||
|
||||
getOut().println("Barn installed as Windows service");
|
||||
getOut().println("Service name: " + winService.getServiceName());
|
||||
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");
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to install service", e);
|
||||
return EXIT_ERROR;
|
||||
} catch (WindowsServiceManager.WindowsServiceException e) {
|
||||
outputError("Failed to install Windows service: " + e.getMessage());
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private Path getEffectiveBarnDir() {
|
||||
if (barnDir != null) {
|
||||
return barnDir;
|
||||
}
|
||||
return ConfigDefaults.getDefaultBaseDir();
|
||||
}
|
||||
|
||||
private Path getEffectiveBinaryPath() {
|
||||
if (binaryPath != null) {
|
||||
return binaryPath;
|
||||
}
|
||||
|
||||
// Try to find barn binary in common locations
|
||||
Path[] candidates = {
|
||||
Path.of("/usr/local/bin/barn"),
|
||||
Path.of("/opt/homebrew/bin/barn"),
|
||||
Path.of(System.getProperty("user.home"), ".local", "bin", "barn"),
|
||||
Path.of(System.getProperty("user.home"), "bin", "barn")
|
||||
};
|
||||
|
||||
for (Path candidate : candidates) {
|
||||
if (Files.isExecutable(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to assuming barn is in PATH
|
||||
return Path.of("barn");
|
||||
}
|
||||
|
||||
private boolean canWriteToPath(Path path) {
|
||||
if (path == null) {
|
||||
return false;
|
||||
}
|
||||
if (Files.exists(path)) {
|
||||
return Files.isWritable(path);
|
||||
}
|
||||
// Check parent
|
||||
return canWriteToPath(path.getParent());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.RandomAccessFile;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to show Barn service logs.
|
||||
*/
|
||||
@Command(
|
||||
name = "logs",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Show service logs"
|
||||
)
|
||||
public class ServiceLogsCommand extends BaseCommand {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServiceLogsCommand.class);
|
||||
private static final String LOG_FILE_NAME = "barn.log";
|
||||
|
||||
@Option(names = {"--follow", "-f"}, description = "Follow log output")
|
||||
private boolean follow;
|
||||
|
||||
@Option(names = {"--lines", "-n"}, description = "Number of lines to show", defaultValue = "100")
|
||||
private int lines;
|
||||
|
||||
@Option(names = {"--barn-dir"}, description = "Barn data directory", hidden = true)
|
||||
private Path barnDir;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
try {
|
||||
Path effectiveBarnDir = getEffectiveBarnDir();
|
||||
Path logFile = effectiveBarnDir.resolve("logs").resolve(LOG_FILE_NAME);
|
||||
|
||||
if (!Files.exists(logFile)) {
|
||||
getOut().println("No log file found at: " + logFile);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
if (follow) {
|
||||
return followLogs(logFile);
|
||||
} else {
|
||||
return tailLogs(logFile);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to read logs", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int tailLogs(Path logFile) throws IOException {
|
||||
List<String> lastLines = readLastLines(logFile, lines);
|
||||
|
||||
for (String line : lastLines) {
|
||||
getOut().println(line);
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
private int followLogs(Path logFile) throws IOException {
|
||||
// First output existing lines
|
||||
tailLogs(logFile);
|
||||
|
||||
// Then follow new content
|
||||
getOut().println("--- Following log output (Ctrl+C to stop) ---");
|
||||
|
||||
try (RandomAccessFile raf = new RandomAccessFile(logFile.toFile(), "r")) {
|
||||
raf.seek(raf.length());
|
||||
|
||||
while (!Thread.currentThread().isInterrupted()) {
|
||||
String line = raf.readLine();
|
||||
if (line != null) {
|
||||
getOut().println(line);
|
||||
} else {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the last N lines from a file efficiently.
|
||||
*/
|
||||
private List<String> readLastLines(Path file, int numLines) throws IOException {
|
||||
List<String> allLines = new ArrayList<>();
|
||||
|
||||
try (BufferedReader reader = Files.newBufferedReader(file)) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
allLines.add(line);
|
||||
}
|
||||
}
|
||||
|
||||
if (allLines.size() <= numLines) {
|
||||
return allLines;
|
||||
}
|
||||
|
||||
return allLines.subList(allLines.size() - numLines, allLines.size());
|
||||
}
|
||||
|
||||
private Path getEffectiveBarnDir() {
|
||||
if (barnDir != null) {
|
||||
return barnDir;
|
||||
}
|
||||
return ConfigDefaults.getDefaultBaseDir();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.ipc.IpcClient;
|
||||
import com.samsonmedia.barn.ipc.IpcException;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to reload the Barn service configuration.
|
||||
*/
|
||||
@Command(
|
||||
name = "reload",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Reload configuration without stopping jobs"
|
||||
)
|
||||
public class ServiceReloadCommand extends BaseCommand {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServiceReloadCommand.class);
|
||||
|
||||
@Option(names = {"--barn-dir"}, description = "Barn data directory", hidden = true)
|
||||
private Path barnDir;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
try {
|
||||
Path effectiveBarnDir = getEffectiveBarnDir();
|
||||
|
||||
// Check if running
|
||||
if (!isServiceRunning(effectiveBarnDir)) {
|
||||
outputError("Barn service is not running");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
// Send reload via IPC
|
||||
Path socketPath = effectiveBarnDir.resolve("barn.sock");
|
||||
if (!Files.exists(socketPath)) {
|
||||
// Fallback: Send SIGHUP signal
|
||||
return sendSighup(effectiveBarnDir);
|
||||
}
|
||||
|
||||
try (IpcClient client = new IpcClient(socketPath)) {
|
||||
String result = client.send("reload", null, String.class);
|
||||
getOut().println("Configuration reloaded");
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IpcException e) {
|
||||
LOG.warn("IPC failed, trying SIGHUP: {}", e.getMessage());
|
||||
return sendSighup(effectiveBarnDir);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to reload configuration", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int sendSighup(Path effectiveBarnDir) throws IOException {
|
||||
Path pidFile = effectiveBarnDir.resolve("barn.pid");
|
||||
if (!Files.exists(pidFile)) {
|
||||
outputError("Cannot send reload signal - no PID file");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
String pidStr = Files.readString(pidFile).trim();
|
||||
long pid = Long.parseLong(pidStr);
|
||||
|
||||
// On Unix, we can send SIGHUP. On Windows, this won't work.
|
||||
String os = System.getProperty("os.name").toLowerCase();
|
||||
if (os.contains("windows")) {
|
||||
outputError("Reload via signal not supported on Windows. IPC socket required.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
ProcessBuilder pb = new ProcessBuilder("kill", "-HUP", String.valueOf(pid));
|
||||
Process process = pb.start();
|
||||
|
||||
try {
|
||||
int exitCode = process.waitFor();
|
||||
if (exitCode != 0) {
|
||||
outputError("Failed to send reload signal");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
outputError("Interrupted while sending reload signal");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
getOut().println("Configuration reloaded");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
private boolean isServiceRunning(Path effectiveBarnDir) {
|
||||
Path pidFile = effectiveBarnDir.resolve("barn.pid");
|
||||
if (!Files.exists(pidFile)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
String pidStr = Files.readString(pidFile).trim();
|
||||
long pid = Long.parseLong(pidStr);
|
||||
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
|
||||
return handle.map(ProcessHandle::isAlive).orElse(false);
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private Path getEffectiveBarnDir() {
|
||||
if (barnDir != null) {
|
||||
return barnDir;
|
||||
}
|
||||
return ConfigDefaults.getDefaultBaseDir();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.execution.ProcessUtils;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to restart the Barn service.
|
||||
*/
|
||||
@Command(
|
||||
name = "restart",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Restart the Barn service"
|
||||
)
|
||||
public class ServiceRestartCommand extends BaseCommand {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServiceRestartCommand.class);
|
||||
private static final long DEFAULT_WAIT_SECONDS = 30;
|
||||
|
||||
@Option(names = {"--force", "-f"}, description = "Force immediate restart")
|
||||
private boolean force;
|
||||
|
||||
@Option(names = {"--barn-dir"}, description = "Barn data directory", hidden = true)
|
||||
private Path barnDir;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
try {
|
||||
Path effectiveBarnDir = getEffectiveBarnDir();
|
||||
|
||||
// Check if running
|
||||
if (!isServiceRunning(effectiveBarnDir)) {
|
||||
outputError("Barn service is not running");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
// Stop the service
|
||||
int stopResult = stopService(effectiveBarnDir);
|
||||
if (stopResult != EXIT_SUCCESS) {
|
||||
outputError("Failed to stop service");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
// Wait a bit for cleanup
|
||||
Thread.sleep(500);
|
||||
|
||||
// Start the service
|
||||
int startResult = startService(effectiveBarnDir);
|
||||
if (startResult != EXIT_SUCCESS) {
|
||||
outputError("Failed to start service after stop");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
getOut().println("Barn service restarted");
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException | InterruptedException e) {
|
||||
outputError("Failed to restart service", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean isServiceRunning(Path effectiveBarnDir) {
|
||||
Path pidFile = effectiveBarnDir.resolve("barn.pid");
|
||||
if (!Files.exists(pidFile)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
String pidStr = Files.readString(pidFile).trim();
|
||||
long pid = Long.parseLong(pidStr);
|
||||
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
|
||||
return handle.map(ProcessHandle::isAlive).orElse(false);
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int stopService(Path effectiveBarnDir) throws IOException {
|
||||
Path pidFile = effectiveBarnDir.resolve("barn.pid");
|
||||
String pidStr = Files.readString(pidFile).trim();
|
||||
long pid = Long.parseLong(pidStr);
|
||||
|
||||
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
|
||||
if (handle.isEmpty()) {
|
||||
Files.deleteIfExists(pidFile);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
ProcessHandle proc = handle.get();
|
||||
|
||||
if (force) {
|
||||
ProcessUtils.killTreeForcibly(pid);
|
||||
} else {
|
||||
proc.destroy();
|
||||
if (!waitForTermination(proc)) {
|
||||
ProcessUtils.killTreeForcibly(pid);
|
||||
}
|
||||
}
|
||||
|
||||
Files.deleteIfExists(pidFile);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
private int startService(Path effectiveBarnDir) throws IOException {
|
||||
String javaHome = System.getProperty("java.home");
|
||||
String classPath = System.getProperty("java.class.path");
|
||||
|
||||
ProcessBuilder pb = new ProcessBuilder(
|
||||
Path.of(javaHome, "bin", "java").toString(),
|
||||
"-cp", classPath,
|
||||
"com.samsonmedia.barn.Main",
|
||||
"service", "start", "--foreground",
|
||||
"--barn-dir", effectiveBarnDir.toString()
|
||||
);
|
||||
|
||||
if (globalOptions != null && globalOptions.getConfigPath().isPresent()) {
|
||||
pb.command().add("--config");
|
||||
pb.command().add(globalOptions.getConfigPath().get().toString());
|
||||
}
|
||||
|
||||
Path logsDir = effectiveBarnDir.resolve("logs");
|
||||
Files.createDirectories(logsDir);
|
||||
Path logFile = logsDir.resolve("barn.log");
|
||||
|
||||
pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile.toFile()));
|
||||
pb.redirectError(ProcessBuilder.Redirect.appendTo(logFile.toFile()));
|
||||
|
||||
pb.start();
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
private boolean waitForTermination(ProcessHandle proc) {
|
||||
long deadline = System.currentTimeMillis() + (DEFAULT_WAIT_SECONDS * 1000);
|
||||
|
||||
while (proc.isAlive() && System.currentTimeMillis() < deadline) {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return !proc.isAlive();
|
||||
}
|
||||
|
||||
private Path getEffectiveBarnDir() {
|
||||
if (barnDir != null) {
|
||||
return barnDir;
|
||||
}
|
||||
return ConfigDefaults.getDefaultBaseDir();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.Config;
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.config.ConfigLoader;
|
||||
import com.samsonmedia.barn.service.BarnService;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to start the Barn service.
|
||||
*/
|
||||
@Command(
|
||||
name = "start",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Start the Barn service"
|
||||
)
|
||||
public class ServiceStartCommand extends BaseCommand {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServiceStartCommand.class);
|
||||
|
||||
@Option(names = {"--foreground", "-f"}, description = "Run in foreground (don't daemonize)")
|
||||
private boolean foreground;
|
||||
|
||||
@Option(names = {"--foreground-test"}, hidden = true, description = "Test mode for foreground")
|
||||
private boolean foregroundTest;
|
||||
|
||||
@Option(names = {"--dry-run"}, hidden = true, description = "Don't actually start, just validate")
|
||||
private boolean dryRun;
|
||||
|
||||
@Option(names = {"--barn-dir"}, description = "Barn data directory", hidden = true)
|
||||
private Path barnDir;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
try {
|
||||
Path effectiveBarnDir = getEffectiveBarnDir();
|
||||
|
||||
// Check if already running
|
||||
if (isServiceRunning(effectiveBarnDir)) {
|
||||
outputError("Barn service is already running");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
if (dryRun) {
|
||||
getOut().println("Barn service would be started (dry run)");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
if (foreground || foregroundTest) {
|
||||
return startForeground(effectiveBarnDir);
|
||||
} else {
|
||||
return startDaemon(effectiveBarnDir);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to start service", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int startForeground(Path effectiveBarnDir) throws IOException {
|
||||
writePidFile(effectiveBarnDir);
|
||||
getOut().println("Barn service started (PID: " + ProcessHandle.current().pid() + ")");
|
||||
|
||||
if (foregroundTest) {
|
||||
// In test mode, just return immediately without blocking
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
Config config = loadConfig(effectiveBarnDir);
|
||||
final BarnService service = new BarnService(config);
|
||||
|
||||
// Set up shutdown hook
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
|
||||
LOG.info("Shutdown signal received");
|
||||
service.stop();
|
||||
deletePidFile(effectiveBarnDir);
|
||||
}));
|
||||
|
||||
try {
|
||||
service.start();
|
||||
service.awaitTermination();
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.info("Service interrupted");
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
private int startDaemon(Path effectiveBarnDir) throws IOException {
|
||||
// For daemonizing, we re-exec with --foreground and nohup
|
||||
// This is a simplified approach; production would use proper daemon techniques
|
||||
String javaHome = System.getProperty("java.home");
|
||||
String classPath = System.getProperty("java.class.path");
|
||||
|
||||
ProcessBuilder pb = new ProcessBuilder(
|
||||
Path.of(javaHome, "bin", "java").toString(),
|
||||
"-cp", classPath,
|
||||
"com.samsonmedia.barn.Main",
|
||||
"service", "start", "--foreground",
|
||||
"--barn-dir", effectiveBarnDir.toString()
|
||||
);
|
||||
|
||||
if (globalOptions != null && globalOptions.getConfigPath().isPresent()) {
|
||||
pb.command().add("--config");
|
||||
pb.command().add(globalOptions.getConfigPath().get().toString());
|
||||
}
|
||||
|
||||
Path logsDir = effectiveBarnDir.resolve("logs");
|
||||
Files.createDirectories(logsDir);
|
||||
Path logFile = logsDir.resolve("barn.log");
|
||||
|
||||
pb.redirectOutput(ProcessBuilder.Redirect.appendTo(logFile.toFile()));
|
||||
pb.redirectError(ProcessBuilder.Redirect.appendTo(logFile.toFile()));
|
||||
|
||||
Process process = pb.start();
|
||||
long pid = process.pid();
|
||||
|
||||
getOut().println("Barn service started (PID: " + pid + ")");
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
private Config loadConfig(Path effectiveBarnDir) throws IOException {
|
||||
if (globalOptions != null && globalOptions.getConfigPath().isPresent()) {
|
||||
Path configPath = globalOptions.getConfigPath().get();
|
||||
if (Files.exists(configPath)) {
|
||||
return ConfigLoader.load(configPath);
|
||||
}
|
||||
}
|
||||
|
||||
// Check for default config file locations
|
||||
Path defaultConfig = effectiveBarnDir.resolve("barn.conf");
|
||||
if (Files.exists(defaultConfig)) {
|
||||
return ConfigLoader.load(defaultConfig);
|
||||
}
|
||||
|
||||
return Config.withDefaults();
|
||||
}
|
||||
|
||||
private boolean isServiceRunning(Path effectiveBarnDir) {
|
||||
Path pidFile = effectiveBarnDir.resolve("barn.pid");
|
||||
if (!Files.exists(pidFile)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
String pidStr = Files.readString(pidFile).trim();
|
||||
long pid = Long.parseLong(pidStr);
|
||||
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
|
||||
return handle.map(ProcessHandle::isAlive).orElse(false);
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private void writePidFile(Path effectiveBarnDir) throws IOException {
|
||||
Files.createDirectories(effectiveBarnDir);
|
||||
Path pidFile = effectiveBarnDir.resolve("barn.pid");
|
||||
Files.writeString(pidFile, String.valueOf(ProcessHandle.current().pid()));
|
||||
}
|
||||
|
||||
private void deletePidFile(Path effectiveBarnDir) {
|
||||
try {
|
||||
Path pidFile = effectiveBarnDir.resolve("barn.pid");
|
||||
Files.deleteIfExists(pidFile);
|
||||
} catch (IOException e) {
|
||||
LOG.warn("Failed to delete PID file: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Path getEffectiveBarnDir() {
|
||||
if (barnDir != null) {
|
||||
return barnDir;
|
||||
}
|
||||
return ConfigDefaults.getDefaultBaseDir();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.config.OperatingSystem;
|
||||
import com.samsonmedia.barn.ipc.IpcClient;
|
||||
import com.samsonmedia.barn.ipc.IpcException;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.platform.linux.SystemdManager;
|
||||
import com.samsonmedia.barn.platform.macos.LaunchdManager;
|
||||
import com.samsonmedia.barn.platform.windows.WindowsServiceManager;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to show the Barn service status.
|
||||
*/
|
||||
@Command(
|
||||
name = "status",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Show service status"
|
||||
)
|
||||
public class ServiceStatusCommand extends BaseCommand {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServiceStatusCommand.class);
|
||||
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd HH:mm:ss")
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
@Option(names = {"--barn-dir"}, description = "Barn data directory", hidden = true)
|
||||
private Path barnDir;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
try {
|
||||
Path effectiveBarnDir = getEffectiveBarnDir();
|
||||
ServiceStatus status = getServiceStatus(effectiveBarnDir);
|
||||
|
||||
outputStatus(status);
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to get service status", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private ServiceStatus getServiceStatus(Path effectiveBarnDir) throws IOException {
|
||||
Path pidFile = effectiveBarnDir.resolve("barn.pid");
|
||||
String serviceManager = getServiceManager();
|
||||
|
||||
if (!Files.exists(pidFile)) {
|
||||
return ServiceStatus.stopped(effectiveBarnDir, serviceManager);
|
||||
}
|
||||
|
||||
String pidStr = Files.readString(pidFile).trim();
|
||||
long pid;
|
||||
try {
|
||||
pid = Long.parseLong(pidStr);
|
||||
} catch (NumberFormatException e) {
|
||||
return ServiceStatus.stopped(effectiveBarnDir, serviceManager);
|
||||
}
|
||||
|
||||
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
|
||||
if (handle.isEmpty() || !handle.get().isAlive()) {
|
||||
// Stale PID file
|
||||
return ServiceStatus.stopped(effectiveBarnDir, serviceManager);
|
||||
}
|
||||
|
||||
ProcessHandle proc = handle.get();
|
||||
Instant startTime = proc.info().startInstant().orElse(Instant.now());
|
||||
|
||||
// Try to get detailed status via IPC
|
||||
Path socketPath = effectiveBarnDir.resolve("barn.sock");
|
||||
if (Files.exists(socketPath)) {
|
||||
try (IpcClient client = new IpcClient(socketPath)) {
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, Object> payload = client.send("get_service_status", null, Map.class);
|
||||
if (payload != null) {
|
||||
int running = getIntValue(payload, "activeJobs", 0);
|
||||
int queued = getIntValue(payload, "queuedJobs", 0);
|
||||
int succeeded = countJobsByState(effectiveBarnDir, JobState.SUCCEEDED);
|
||||
int failed = countJobsByState(effectiveBarnDir, JobState.FAILED);
|
||||
int canceled = countJobsByState(effectiveBarnDir, JobState.CANCELED);
|
||||
int total = countTotalJobs(effectiveBarnDir);
|
||||
|
||||
return ServiceStatus.running(pid, startTime, running, queued, succeeded, failed,
|
||||
canceled, total, effectiveBarnDir, serviceManager);
|
||||
}
|
||||
} catch (IpcException e) {
|
||||
LOG.debug("IPC failed, using basic status: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: Basic status from repository
|
||||
int total = countTotalJobs(effectiveBarnDir);
|
||||
int running = countJobsByState(effectiveBarnDir, JobState.RUNNING);
|
||||
int queued = countJobsByState(effectiveBarnDir, JobState.QUEUED);
|
||||
int succeeded = countJobsByState(effectiveBarnDir, JobState.SUCCEEDED);
|
||||
int failed = countJobsByState(effectiveBarnDir, JobState.FAILED);
|
||||
int canceled = countJobsByState(effectiveBarnDir, JobState.CANCELED);
|
||||
|
||||
return ServiceStatus.running(pid, startTime, running, queued, succeeded, failed, canceled,
|
||||
total, effectiveBarnDir, serviceManager);
|
||||
}
|
||||
|
||||
private int getIntValue(Map<String, Object> map, String key, int defaultValue) {
|
||||
Object value = map.get(key);
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).intValue();
|
||||
}
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
private int countTotalJobs(Path effectiveBarnDir) throws IOException {
|
||||
BarnDirectories dirs = new BarnDirectories(effectiveBarnDir);
|
||||
if (!Files.exists(dirs.getJobsDir())) {
|
||||
return 0;
|
||||
}
|
||||
JobRepository repository = new JobRepository(dirs);
|
||||
return repository.findAll().size();
|
||||
}
|
||||
|
||||
private int countJobsByState(Path effectiveBarnDir, JobState state) throws IOException {
|
||||
BarnDirectories dirs = new BarnDirectories(effectiveBarnDir);
|
||||
if (!Files.exists(dirs.getJobsDir())) {
|
||||
return 0;
|
||||
}
|
||||
JobRepository repository = new JobRepository(dirs);
|
||||
return repository.findByState(state).size();
|
||||
}
|
||||
|
||||
private void outputStatus(ServiceStatus status) {
|
||||
OutputFormat format = globalOptions != null
|
||||
? globalOptions.getOutputFormat()
|
||||
: OutputFormat.HUMAN;
|
||||
|
||||
switch (format) {
|
||||
case HUMAN -> outputHumanFormat(status);
|
||||
case JSON -> output(status.toMap());
|
||||
case XML -> output(status.toMap());
|
||||
default -> outputHumanFormat(status);
|
||||
}
|
||||
}
|
||||
|
||||
private void outputHumanFormat(ServiceStatus status) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
sb.append("Barn Service Status\n");
|
||||
sb.append("==================\n");
|
||||
|
||||
String runningStatus = status.running ? "running" : "stopped";
|
||||
if (status.serviceManager != null) {
|
||||
runningStatus += " (" + status.serviceManager + " managed)";
|
||||
}
|
||||
sb.append(String.format("Status: %s%n", runningStatus));
|
||||
|
||||
if (status.running) {
|
||||
sb.append(String.format("PID: %d%n", status.pid));
|
||||
sb.append(String.format("Uptime: %s%n", formatUptime(status.uptimeSeconds)));
|
||||
sb.append(String.format("Started: %s%n", DATE_FORMAT.format(status.startedAt)));
|
||||
sb.append("\n");
|
||||
sb.append("Jobs:\n");
|
||||
sb.append(String.format(" Running: %d%n", status.runningJobs));
|
||||
sb.append(String.format(" Queued: %d%n", status.queuedJobs));
|
||||
sb.append(String.format(" Succeeded: %d%n", status.succeededJobs));
|
||||
sb.append(String.format(" Failed: %d%n", status.failedJobs));
|
||||
sb.append(String.format(" Canceled: %d%n", status.canceledJobs));
|
||||
sb.append(String.format(" Total: %d%n", status.totalJobs));
|
||||
}
|
||||
|
||||
sb.append("\n");
|
||||
sb.append(String.format("Data Dir: %s%n", status.dataDir));
|
||||
|
||||
getOut().println(sb.toString().trim());
|
||||
}
|
||||
|
||||
private String formatUptime(long seconds) {
|
||||
if (seconds < 60) {
|
||||
return seconds + " seconds";
|
||||
} else if (seconds < 3600) {
|
||||
return (seconds / 60) + " minutes";
|
||||
} else if (seconds < 86400) {
|
||||
long hours = seconds / 3600;
|
||||
long minutes = (seconds % 3600) / 60;
|
||||
return hours + " hours, " + minutes + " minutes";
|
||||
} else {
|
||||
long days = seconds / 86400;
|
||||
long hours = (seconds % 86400) / 3600;
|
||||
return days + " days, " + hours + " hours";
|
||||
}
|
||||
}
|
||||
|
||||
private Path getEffectiveBarnDir() {
|
||||
if (barnDir != null) {
|
||||
return barnDir;
|
||||
}
|
||||
return ConfigDefaults.getDefaultBaseDir();
|
||||
}
|
||||
|
||||
private String getServiceManager() {
|
||||
OperatingSystem os = OperatingSystem.current();
|
||||
|
||||
if (os == OperatingSystem.MACOS) {
|
||||
LaunchdManager launchd = new LaunchdManager();
|
||||
if (launchd.isLoaded()) {
|
||||
return "launchd";
|
||||
}
|
||||
} else if (os == OperatingSystem.LINUX) {
|
||||
if (SystemdManager.hasSystemd()) {
|
||||
SystemdManager systemd = new SystemdManager();
|
||||
if (systemd.isActive(false) || systemd.isActive(true)) {
|
||||
return "systemd";
|
||||
}
|
||||
}
|
||||
} else if (os == OperatingSystem.WINDOWS) {
|
||||
if (WindowsServiceManager.hasWindowsServices()) {
|
||||
WindowsServiceManager winService = new WindowsServiceManager();
|
||||
if (winService.isRunning()) {
|
||||
return "Windows SCM";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Service status data.
|
||||
*/
|
||||
private static final class ServiceStatus {
|
||||
final boolean running;
|
||||
final long pid;
|
||||
final Instant startedAt;
|
||||
final long uptimeSeconds;
|
||||
final int runningJobs;
|
||||
final int queuedJobs;
|
||||
final int succeededJobs;
|
||||
final int failedJobs;
|
||||
final int canceledJobs;
|
||||
final int totalJobs;
|
||||
final Path dataDir;
|
||||
final String serviceManager;
|
||||
|
||||
private ServiceStatus(boolean running, long pid, Instant startedAt, long uptimeSeconds,
|
||||
int runningJobs, int queuedJobs, int succeededJobs, int failedJobs, int canceledJobs,
|
||||
int totalJobs, Path dataDir, String serviceManager) {
|
||||
this.running = running;
|
||||
this.pid = pid;
|
||||
this.startedAt = startedAt;
|
||||
this.uptimeSeconds = uptimeSeconds;
|
||||
this.runningJobs = runningJobs;
|
||||
this.queuedJobs = queuedJobs;
|
||||
this.succeededJobs = succeededJobs;
|
||||
this.failedJobs = failedJobs;
|
||||
this.canceledJobs = canceledJobs;
|
||||
this.totalJobs = totalJobs;
|
||||
this.dataDir = dataDir;
|
||||
this.serviceManager = serviceManager;
|
||||
}
|
||||
|
||||
static ServiceStatus stopped(Path dataDir, String serviceManager) {
|
||||
return new ServiceStatus(false, 0, null, 0, 0, 0, 0, 0, 0, 0, dataDir, serviceManager);
|
||||
}
|
||||
|
||||
static ServiceStatus running(long pid, Instant startedAt, int runningJobs, int queuedJobs,
|
||||
int succeededJobs, int failedJobs, int canceledJobs, int totalJobs,
|
||||
Path dataDir, String serviceManager) {
|
||||
long uptime = Duration.between(startedAt, Instant.now()).getSeconds();
|
||||
return new ServiceStatus(true, pid, startedAt, uptime, runningJobs, queuedJobs,
|
||||
succeededJobs, failedJobs, canceledJobs, totalJobs, dataDir, serviceManager);
|
||||
}
|
||||
|
||||
Map<String, Object> toMap() {
|
||||
Map<String, Object> map = new LinkedHashMap<>();
|
||||
map.put("status", running ? "running" : "stopped");
|
||||
map.put("running", running);
|
||||
|
||||
if (running) {
|
||||
map.put("pid", pid);
|
||||
map.put("uptime_seconds", uptimeSeconds);
|
||||
map.put("started_at", startedAt != null ? startedAt.toString() : null);
|
||||
|
||||
Map<String, Object> jobs = new LinkedHashMap<>();
|
||||
jobs.put("running", runningJobs);
|
||||
jobs.put("queued", queuedJobs);
|
||||
jobs.put("succeeded", succeededJobs);
|
||||
jobs.put("failed", failedJobs);
|
||||
jobs.put("canceled", canceledJobs);
|
||||
jobs.put("total", totalJobs);
|
||||
map.put("jobs", jobs);
|
||||
}
|
||||
|
||||
map.put("data_dir", dataDir.toString());
|
||||
if (serviceManager != null) {
|
||||
map.put("managed_by", serviceManager);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
import com.samsonmedia.barn.execution.ProcessUtils;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to stop the Barn service.
|
||||
*/
|
||||
@Command(
|
||||
name = "stop",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Stop the Barn service"
|
||||
)
|
||||
public class ServiceStopCommand extends BaseCommand {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(ServiceStopCommand.class);
|
||||
private static final long DEFAULT_WAIT_SECONDS = 30;
|
||||
|
||||
@Option(names = {"--force", "-f"}, description = "Force immediate stop (SIGKILL)")
|
||||
private boolean force;
|
||||
|
||||
@Option(names = {"--barn-dir"}, description = "Barn data directory", hidden = true)
|
||||
private Path barnDir;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
try {
|
||||
Path effectiveBarnDir = getEffectiveBarnDir();
|
||||
Path pidFile = effectiveBarnDir.resolve("barn.pid");
|
||||
|
||||
if (!Files.exists(pidFile)) {
|
||||
if (force) {
|
||||
// Force mode - silently succeed if not running
|
||||
getOut().println("Barn service was not running");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
outputError("Barn service is not running");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
String pidStr = Files.readString(pidFile).trim();
|
||||
long pid = Long.parseLong(pidStr);
|
||||
|
||||
Optional<ProcessHandle> handle = ProcessHandle.of(pid);
|
||||
if (handle.isEmpty() || !handle.get().isAlive()) {
|
||||
// Process not running but PID file exists - clean up
|
||||
Files.deleteIfExists(pidFile);
|
||||
if (force) {
|
||||
getOut().println("Barn service was not running");
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
outputError("Barn service is not running (stale PID file removed)");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
ProcessHandle proc = handle.get();
|
||||
|
||||
if (force) {
|
||||
// Force kill
|
||||
ProcessUtils.killTreeForcibly(pid);
|
||||
Files.deleteIfExists(pidFile);
|
||||
getOut().println("Barn service force stopped");
|
||||
} else {
|
||||
// Graceful shutdown - send SIGTERM
|
||||
boolean destroyed = proc.destroy();
|
||||
if (!destroyed) {
|
||||
outputError("Failed to send termination signal");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
// Wait for termination
|
||||
boolean terminated = waitForTermination(proc);
|
||||
if (!terminated) {
|
||||
LOG.warn("Service did not stop gracefully, forcing");
|
||||
ProcessUtils.killTreeForcibly(pid);
|
||||
}
|
||||
|
||||
Files.deleteIfExists(pidFile);
|
||||
getOut().println("Barn service stopped");
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException | NumberFormatException e) {
|
||||
outputError("Failed to stop service", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean waitForTermination(ProcessHandle proc) {
|
||||
long deadline = System.currentTimeMillis() + (DEFAULT_WAIT_SECONDS * 1000);
|
||||
|
||||
while (proc.isAlive() && System.currentTimeMillis() < deadline) {
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return !proc.isAlive();
|
||||
}
|
||||
|
||||
private Path getEffectiveBarnDir() {
|
||||
if (barnDir != null) {
|
||||
return barnDir;
|
||||
}
|
||||
return ConfigDefaults.getDefaultBaseDir();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.OperatingSystem;
|
||||
import com.samsonmedia.barn.platform.linux.SystemdManager;
|
||||
import com.samsonmedia.barn.platform.macos.LaunchdManager;
|
||||
import com.samsonmedia.barn.platform.windows.WindowsServiceManager;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to uninstall Barn system service.
|
||||
*
|
||||
* <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>
|
||||
* </ul>
|
||||
*/
|
||||
@Command(
|
||||
name = "uninstall",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Uninstall Barn system service"
|
||||
)
|
||||
public class ServiceUninstallCommand extends BaseCommand {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.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;
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
OperatingSystem os = OperatingSystem.current();
|
||||
|
||||
return switch (os) {
|
||||
case MACOS -> uninstallMacOs();
|
||||
case LINUX -> uninstallLinux();
|
||||
case WINDOWS -> uninstallWindows();
|
||||
};
|
||||
}
|
||||
|
||||
private int uninstallMacOs() {
|
||||
LaunchdManager launchd = new LaunchdManager();
|
||||
|
||||
Path plistPath = userService ? launchd.getUserAgentPath() : 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.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
try {
|
||||
// Stop the service first if it's running
|
||||
if (launchd.isLoaded()) {
|
||||
try {
|
||||
launchd.unload(plistPath);
|
||||
} catch (LaunchdManager.LaunchdException e) {
|
||||
if (!force) {
|
||||
outputError("Failed to stop service: " + e.getMessage()
|
||||
+ ". Use --force to uninstall anyway.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
LOG.warn("Force uninstalling despite error: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the plist file
|
||||
if (!launchd.deletePlist(plistPath)) {
|
||||
if (!force) {
|
||||
outputError("Failed to remove plist file: " + plistPath);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
String serviceType = userService ? "user agent" : "system daemon";
|
||||
getOut().println("Barn " + serviceType + " uninstalled successfully");
|
||||
getOut().println("Removed: " + plistPath);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (LaunchdManager.LaunchdException e) {
|
||||
outputError("Failed to uninstall service: " + e.getMessage());
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int uninstallLinux() {
|
||||
if (!SystemdManager.hasSystemd()) {
|
||||
outputError("Systemd is not available on this system");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
SystemdManager systemd = new SystemdManager();
|
||||
Path unitPath = userService ? systemd.getUserServicePath() : 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.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
try {
|
||||
// Stop and disable the service first
|
||||
if (systemd.isActive(userService)) {
|
||||
try {
|
||||
systemd.stop(userService);
|
||||
} catch (SystemdManager.SystemdException e) {
|
||||
if (!force) {
|
||||
outputError("Failed to stop service: " + e.getMessage()
|
||||
+ ". Use --force to uninstall anyway.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
LOG.warn("Force uninstalling despite error: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
if (systemd.isEnabled(userService)) {
|
||||
try {
|
||||
systemd.disable(userService);
|
||||
} catch (SystemdManager.SystemdException e) {
|
||||
LOG.warn("Failed to disable service: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Remove the unit file
|
||||
if (!systemd.deleteUnitFile(unitPath)) {
|
||||
if (!force) {
|
||||
outputError("Failed to remove unit file: " + unitPath);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
// Reload systemd
|
||||
try {
|
||||
systemd.daemonReload(userService);
|
||||
} 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("Removed: " + unitPath);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (SystemdManager.SystemdException e) {
|
||||
outputError("Failed to uninstall service: " + e.getMessage());
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int uninstallWindows() {
|
||||
if (!WindowsServiceManager.hasWindowsServices()) {
|
||||
outputError("Windows services are not available on this system");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
WindowsServiceManager winService = new WindowsServiceManager();
|
||||
|
||||
// Check if installed
|
||||
if (!winService.isInstalled()) {
|
||||
outputError("Barn service is not installed");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
// Check for admin privileges
|
||||
if (!WindowsServiceManager.isAdmin()) {
|
||||
outputError("Windows service uninstallation requires administrator privileges. "
|
||||
+ "Please run Command Prompt as Administrator and try again.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
try {
|
||||
// Stop the service first if it's running
|
||||
if (winService.isRunning()) {
|
||||
try {
|
||||
winService.stop();
|
||||
} catch (WindowsServiceManager.WindowsServiceException e) {
|
||||
if (!force) {
|
||||
outputError("Failed to stop service: " + e.getMessage()
|
||||
+ ". Use --force to uninstall anyway.");
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
LOG.warn("Force uninstalling despite error: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Uninstall the service
|
||||
winService.uninstall();
|
||||
|
||||
getOut().println("Barn Windows service uninstalled successfully");
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (WindowsServiceManager.WindowsServiceException e) {
|
||||
outputError("Failed to uninstall service: " + e.getMessage());
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private boolean canWriteToPath(Path path) {
|
||||
if (path == null) {
|
||||
return false;
|
||||
}
|
||||
return Files.isWritable(path);
|
||||
}
|
||||
}
|
||||
@@ -1,26 +1,295 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.Comparator;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
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.state.BarnDirectories;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Model.CommandSpec;
|
||||
import picocli.CommandLine.Spec;
|
||||
import picocli.CommandLine.Option;
|
||||
|
||||
/**
|
||||
* Command to show status of all jobs.
|
||||
*
|
||||
* <p>Placeholder implementation - full implementation in ticket #10.
|
||||
* <p>Lists jobs with optional filtering by tag, state, or limit.
|
||||
*/
|
||||
@Command(
|
||||
name = "status",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Show status of all jobs"
|
||||
)
|
||||
public class StatusCommand implements Runnable {
|
||||
public class StatusCommand extends BaseCommand {
|
||||
|
||||
@Spec
|
||||
private CommandSpec spec;
|
||||
private static final Logger LOG = LoggerFactory.getLogger(StatusCommand.class);
|
||||
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd HH:mm:ss")
|
||||
.withZone(ZoneId.systemDefault());
|
||||
|
||||
@Option(names = {"--tag", "-t"}, description = "Filter by tag")
|
||||
private String tag;
|
||||
|
||||
@Option(names = {"--state", "-s"}, description = "Filter by state")
|
||||
private JobState state;
|
||||
|
||||
@Option(names = {"--limit", "-n"}, description = "Limit number of results")
|
||||
private Integer limit;
|
||||
|
||||
@Option(names = {"--barn-dir"}, description = "Barn data directory", hidden = true)
|
||||
private Path barnDir;
|
||||
|
||||
/**
|
||||
* Sets the barn directory (for testing).
|
||||
*
|
||||
* @param barnDir the barn directory path
|
||||
*/
|
||||
public void setBarnDir(Path barnDir) {
|
||||
this.barnDir = barnDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
spec.commandLine().getOut().println("Status command not yet implemented");
|
||||
public Integer call() {
|
||||
if (isOffline()) {
|
||||
return runOffline();
|
||||
}
|
||||
|
||||
return runWithService();
|
||||
}
|
||||
|
||||
private int runOffline() {
|
||||
try {
|
||||
BarnDirectories dirs = getBarnDirectories();
|
||||
JobRepository repository = new JobRepository(dirs);
|
||||
|
||||
// Get all jobs
|
||||
List<Job> jobs = repository.findAll();
|
||||
|
||||
// Apply filters
|
||||
jobs = applyFilters(jobs);
|
||||
|
||||
// Sort by creation time (newest first)
|
||||
jobs = jobs.stream()
|
||||
.sorted(Comparator.comparing(Job::createdAt).reversed())
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// Apply limit
|
||||
if (limit != null && limit > 0 && jobs.size() > limit) {
|
||||
jobs = jobs.subList(0, limit);
|
||||
}
|
||||
|
||||
// Output
|
||||
outputStatus(jobs);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to get job status", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int runWithService() {
|
||||
try (IpcClient client = new IpcClient(getBarnDirectories().getSocketPath())) {
|
||||
// Build request payload
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
if (tag != null) {
|
||||
payload.put("tag", tag);
|
||||
}
|
||||
if (state != null) {
|
||||
payload.put("state", state.name());
|
||||
}
|
||||
if (limit != null) {
|
||||
payload.put("limit", limit);
|
||||
}
|
||||
|
||||
// Send request and get response
|
||||
Object response = client.send("get_status", payload, Object.class);
|
||||
LOG.debug("IPC response type: {}, value: {}",
|
||||
response != null ? response.getClass().getName() : "null", response);
|
||||
|
||||
// Convert response to List<Job>
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
|
||||
List<Job> jobs = mapper.convertValue(response, new TypeReference<List<Job>>() { });
|
||||
|
||||
// Output
|
||||
outputStatus(jobs);
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IpcException e) {
|
||||
if ("SERVICE_NOT_RUNNING".equals(e.getCode())) {
|
||||
outputError("Service not running. Start with: barn service start\n"
|
||||
+ "Or use --offline to run without the service.");
|
||||
} else {
|
||||
outputError("IPC error: " + e.getMessage());
|
||||
}
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private List<Job> applyFilters(List<Job> jobs) {
|
||||
return jobs.stream()
|
||||
.filter(job -> tag == null || tag.equals(job.tag()))
|
||||
.filter(job -> state == null || state == job.state())
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private BarnDirectories getBarnDirectories() {
|
||||
if (barnDir != null) {
|
||||
return new BarnDirectories(barnDir);
|
||||
}
|
||||
Path defaultDir = ConfigDefaults.getDefaultBaseDir();
|
||||
return new BarnDirectories(defaultDir);
|
||||
}
|
||||
|
||||
private void outputStatus(List<Job> jobs) {
|
||||
OutputFormat format = globalOptions != null
|
||||
? globalOptions.getOutputFormat()
|
||||
: OutputFormat.HUMAN;
|
||||
|
||||
if (jobs.isEmpty()) {
|
||||
if (format == OutputFormat.HUMAN) {
|
||||
getOut().println("No jobs found.");
|
||||
} else {
|
||||
outputStructuredEmpty(format);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
switch (format) {
|
||||
case HUMAN -> outputHumanFormat(jobs);
|
||||
case JSON -> outputJsonFormat(jobs);
|
||||
case XML -> outputXmlFormat(jobs);
|
||||
default -> outputHumanFormat(jobs);
|
||||
}
|
||||
}
|
||||
|
||||
private void outputHumanFormat(List<Job> jobs) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
// Calculate column widths
|
||||
int idWidth = Math.max(10, jobs.stream().mapToInt(j -> j.id().length()).max().orElse(10));
|
||||
int tagWidth = Math.max(3, jobs.stream()
|
||||
.mapToInt(j -> j.tag() != null ? j.tag().length() : 1)
|
||||
.max().orElse(3));
|
||||
|
||||
// Header
|
||||
sb.append(String.format("%-" + idWidth + "s %-9s %-" + tagWidth + "s %-19s %-4s %-8s%n",
|
||||
"ID", "STATE", "TAG", "CREATED", "EXIT", "PID"));
|
||||
|
||||
// Rows
|
||||
for (Job job : jobs) {
|
||||
sb.append(String.format("%-" + idWidth + "s %-9s %-" + tagWidth + "s %-19s %-4s %-8s%n",
|
||||
job.id(),
|
||||
job.state().toString().toLowerCase(),
|
||||
job.tag() != null ? job.tag() : "-",
|
||||
formatTimestamp(job.createdAt()),
|
||||
job.exitCode() != null ? job.exitCode().toString() : "-",
|
||||
job.pid() != null ? job.pid().toString() : "-"));
|
||||
}
|
||||
|
||||
// Summary
|
||||
sb.append("\n");
|
||||
sb.append(buildSummary(jobs));
|
||||
|
||||
getOut().println(sb.toString().trim());
|
||||
}
|
||||
|
||||
private void outputJsonFormat(List<Job> jobs) {
|
||||
// Create structured response
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
response.put("jobs", jobs);
|
||||
response.put("summary", buildSummaryMap(jobs));
|
||||
|
||||
output(response);
|
||||
}
|
||||
|
||||
private void outputXmlFormat(List<Job> jobs) {
|
||||
// Use standard formatter with jobs list wrapped
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
response.put("jobs", jobs);
|
||||
response.put("summary", buildSummaryMap(jobs));
|
||||
|
||||
output(response);
|
||||
}
|
||||
|
||||
private void outputStructuredEmpty(OutputFormat format) {
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
response.put("jobs", List.of());
|
||||
response.put("summary", Map.of("total", 0));
|
||||
|
||||
output(response);
|
||||
}
|
||||
|
||||
private String buildSummary(List<Job> jobs) {
|
||||
Map<JobState, Long> counts = jobs.stream()
|
||||
.collect(Collectors.groupingBy(Job::state, Collectors.counting()));
|
||||
|
||||
StringBuilder summary = new StringBuilder();
|
||||
summary.append("Total: ").append(jobs.size()).append(" job");
|
||||
if (jobs.size() != 1) {
|
||||
summary.append("s");
|
||||
}
|
||||
|
||||
if (!counts.isEmpty()) {
|
||||
summary.append(" (");
|
||||
boolean first = true;
|
||||
for (JobState s : JobState.values()) {
|
||||
long count = counts.getOrDefault(s, 0L);
|
||||
if (count > 0) {
|
||||
if (!first) {
|
||||
summary.append(", ");
|
||||
}
|
||||
summary.append(count).append(" ").append(s.toString().toLowerCase());
|
||||
first = false;
|
||||
}
|
||||
}
|
||||
summary.append(")");
|
||||
}
|
||||
|
||||
return summary.toString();
|
||||
}
|
||||
|
||||
private Map<String, Object> buildSummaryMap(List<Job> jobs) {
|
||||
Map<JobState, Long> counts = jobs.stream()
|
||||
.collect(Collectors.groupingBy(Job::state, Collectors.counting()));
|
||||
|
||||
Map<String, Object> summary = new LinkedHashMap<>();
|
||||
summary.put("total", jobs.size());
|
||||
|
||||
for (JobState s : JobState.values()) {
|
||||
summary.put(s.toString().toLowerCase(), counts.getOrDefault(s, 0L));
|
||||
}
|
||||
|
||||
return summary;
|
||||
}
|
||||
|
||||
private String formatTimestamp(Instant timestamp) {
|
||||
if (timestamp == null) {
|
||||
return "-";
|
||||
}
|
||||
return DATE_FORMAT.format(timestamp);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,389 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.ZoneId;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||
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.monitoring.UsageLogger;
|
||||
import com.samsonmedia.barn.monitoring.UsageRecord;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
import picocli.CommandLine.Command;
|
||||
import picocli.CommandLine.Option;
|
||||
import picocli.CommandLine.Parameters;
|
||||
|
||||
/**
|
||||
* Command to show resource usage for a job.
|
||||
*/
|
||||
@Command(
|
||||
name = "usage",
|
||||
mixinStandardHelpOptions = true,
|
||||
description = "Show resource usage for a job"
|
||||
)
|
||||
public class UsageCommand extends BaseCommand {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(UsageCommand.class);
|
||||
private static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter
|
||||
.ofPattern("yyyy-MM-dd HH:mm:ss")
|
||||
.withZone(ZoneId.systemDefault());
|
||||
private static final int DEFAULT_LIMIT = 50;
|
||||
|
||||
@Parameters(index = "0", description = "Job ID")
|
||||
private String jobId;
|
||||
|
||||
@Option(names = {"--limit", "-n"}, description = "Limit number of records (default: ${DEFAULT-VALUE})")
|
||||
private int limit = DEFAULT_LIMIT;
|
||||
|
||||
@Option(names = {"--csv"}, description = "Output raw CSV data")
|
||||
private boolean rawCsv;
|
||||
|
||||
@Option(names = {"--summary"}, description = "Show summary statistics only")
|
||||
private boolean summaryOnly;
|
||||
|
||||
// For testing
|
||||
private Path barnDir;
|
||||
|
||||
/**
|
||||
* Sets the barn directory (for testing).
|
||||
*
|
||||
* @param barnDir the barn directory path
|
||||
*/
|
||||
public void setBarnDir(Path barnDir) {
|
||||
this.barnDir = barnDir;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Integer call() {
|
||||
if (isOffline()) {
|
||||
return runOffline();
|
||||
}
|
||||
return runWithService();
|
||||
}
|
||||
|
||||
private int runOffline() {
|
||||
try {
|
||||
BarnDirectories dirs = getBarnDirectories();
|
||||
JobRepository repository = new JobRepository(dirs);
|
||||
|
||||
Optional<Job> jobOpt = repository.findById(jobId);
|
||||
if (jobOpt.isEmpty()) {
|
||||
outputError("Job not found: " + jobId);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
Path usageFile = dirs.getJobLogsDir(jobId).resolve(UsageLogger.USAGE_LOG_FILENAME);
|
||||
if (!Files.exists(usageFile)) {
|
||||
outputError("No usage data available for job: " + jobId);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
List<UsageRecord> records = loadUsageRecords(usageFile);
|
||||
if (records.isEmpty()) {
|
||||
outputError("No usage data available for job: " + jobId);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
if (rawCsv) {
|
||||
outputRawCsv(usageFile);
|
||||
} else {
|
||||
outputUsage(records);
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to read usage data", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private int runWithService() {
|
||||
try (IpcClient client = new IpcClient(getBarnDirectories().getSocketPath())) {
|
||||
// Verify job exists via IPC
|
||||
Map<String, Object> payload = new LinkedHashMap<>();
|
||||
payload.put("jobId", jobId);
|
||||
client.send("get_job", payload, Object.class);
|
||||
|
||||
// Job exists, read usage data from filesystem
|
||||
BarnDirectories dirs = getBarnDirectories();
|
||||
Path usageFile = dirs.getJobLogsDir(jobId).resolve(UsageLogger.USAGE_LOG_FILENAME);
|
||||
|
||||
if (!Files.exists(usageFile)) {
|
||||
outputError("No usage data available for job: " + jobId);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
List<UsageRecord> records = loadUsageRecords(usageFile);
|
||||
if (records.isEmpty()) {
|
||||
outputError("No usage data available for job: " + jobId);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
|
||||
if (rawCsv) {
|
||||
outputRawCsv(usageFile);
|
||||
} else {
|
||||
outputUsage(records);
|
||||
}
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
|
||||
} catch (IpcException e) {
|
||||
if ("SERVICE_NOT_RUNNING".equals(e.getCode())) {
|
||||
outputError("Service not running. Start with: barn service start\n"
|
||||
+ "Or use --offline to run without the service.");
|
||||
} else if ("NOT_FOUND".equals(e.getCode())) {
|
||||
outputError("Job not found: " + jobId);
|
||||
} else {
|
||||
outputError("IPC error: " + e.getMessage());
|
||||
}
|
||||
return EXIT_ERROR;
|
||||
} catch (IOException e) {
|
||||
outputError("Failed to read usage data", e);
|
||||
return EXIT_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
private BarnDirectories getBarnDirectories() {
|
||||
if (barnDir != null) {
|
||||
return new BarnDirectories(barnDir);
|
||||
}
|
||||
Path defaultDir = ConfigDefaults.getDefaultBaseDir();
|
||||
return new BarnDirectories(defaultDir);
|
||||
}
|
||||
|
||||
private List<UsageRecord> loadUsageRecords(Path usageFile) throws IOException {
|
||||
List<UsageRecord> records = new ArrayList<>();
|
||||
|
||||
try (Stream<String> lines = Files.lines(usageFile)) {
|
||||
List<String> lineList = lines.collect(Collectors.toList());
|
||||
|
||||
// Skip header
|
||||
for (int i = 1; i < lineList.size(); i++) {
|
||||
try {
|
||||
records.add(UsageRecord.fromCsvLine(lineList.get(i)));
|
||||
} catch (Exception e) {
|
||||
LOG.debug("Skipping invalid line: {}", lineList.get(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return records;
|
||||
}
|
||||
|
||||
private void outputRawCsv(Path usageFile) throws IOException {
|
||||
String content = Files.readString(usageFile);
|
||||
getOut().print(content);
|
||||
}
|
||||
|
||||
private void outputUsage(List<UsageRecord> records) {
|
||||
OutputFormat format = globalOptions != null
|
||||
? globalOptions.getOutputFormat()
|
||||
: OutputFormat.HUMAN;
|
||||
|
||||
// Apply limit (take last N records)
|
||||
if (limit > 0 && records.size() > limit) {
|
||||
records = records.subList(records.size() - limit, records.size());
|
||||
}
|
||||
|
||||
switch (format) {
|
||||
case HUMAN -> outputHumanFormat(records);
|
||||
case JSON -> outputJsonFormat(records);
|
||||
case XML -> outputXmlFormat(records);
|
||||
default -> outputHumanFormat(records);
|
||||
}
|
||||
}
|
||||
|
||||
private void outputHumanFormat(List<UsageRecord> records) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
|
||||
sb.append("Resource Usage for Job: ").append(jobId).append("\n");
|
||||
sb.append("================================================================================\n\n");
|
||||
|
||||
// Summary
|
||||
UsageSummary summary = calculateSummary(records);
|
||||
sb.append("Summary (").append(records.size()).append(" samples):\n");
|
||||
sb.append(String.format(" CPU: avg=%.1f%% max=%.1f%% min=%.1f%%%n",
|
||||
summary.avgCpu, summary.maxCpu, summary.minCpu));
|
||||
sb.append(String.format(" Memory: avg=%s max=%s min=%s%n",
|
||||
UsageRecord.formatBytes((long) summary.avgMemory),
|
||||
UsageRecord.formatBytes(summary.maxMemory),
|
||||
UsageRecord.formatBytes(summary.minMemory)));
|
||||
sb.append(String.format(" Disk: max=%s%n",
|
||||
UsageRecord.formatBytes(summary.maxDisk)));
|
||||
|
||||
if (summary.hasGpu) {
|
||||
sb.append(String.format(" GPU: avg=%.1f%% max=%.1f%%%n",
|
||||
summary.avgGpu, summary.maxGpu));
|
||||
sb.append(String.format(" GPU Mem: max=%s%n",
|
||||
UsageRecord.formatBytes(summary.maxGpuMemory)));
|
||||
}
|
||||
|
||||
if (!summaryOnly) {
|
||||
sb.append("\nRecent Samples:\n");
|
||||
sb.append(String.format("%-25s %7s %12s %12s", "TIMESTAMP", "CPU %", "MEMORY", "DISK"));
|
||||
|
||||
if (summary.hasGpu) {
|
||||
sb.append(String.format(" %7s %12s", "GPU %", "GPU MEM"));
|
||||
}
|
||||
sb.append("\n");
|
||||
|
||||
for (UsageRecord record : records) {
|
||||
sb.append(String.format("%-25s %7.1f %12s %12s",
|
||||
DATE_FORMAT.format(record.timestamp()),
|
||||
record.cpuPercent(),
|
||||
UsageRecord.formatBytes(record.memoryBytes()),
|
||||
UsageRecord.formatBytes(record.diskBytes())));
|
||||
|
||||
if (summary.hasGpu && record.gpuPercent() != null) {
|
||||
sb.append(String.format(" %7.1f %12s",
|
||||
record.gpuPercent(),
|
||||
UsageRecord.formatBytes(record.gpuMemoryBytes() != null ? record.gpuMemoryBytes() : 0)));
|
||||
}
|
||||
sb.append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
getOut().println(sb.toString().trim());
|
||||
}
|
||||
|
||||
private void outputJsonFormat(List<UsageRecord> records) {
|
||||
Map<String, Object> response = buildResponseMap(records);
|
||||
output(response);
|
||||
}
|
||||
|
||||
private void outputXmlFormat(List<UsageRecord> records) {
|
||||
Map<String, Object> response = buildResponseMap(records);
|
||||
output(response);
|
||||
}
|
||||
|
||||
private Map<String, Object> buildResponseMap(List<UsageRecord> records) {
|
||||
Map<String, Object> response = new LinkedHashMap<>();
|
||||
response.put("jobId", jobId);
|
||||
|
||||
UsageSummary summary = calculateSummary(records);
|
||||
Map<String, Object> summaryMap = new LinkedHashMap<>();
|
||||
summaryMap.put("sampleCount", records.size());
|
||||
summaryMap.put("cpu", Map.of(
|
||||
"avg", summary.avgCpu,
|
||||
"max", summary.maxCpu,
|
||||
"min", summary.minCpu
|
||||
));
|
||||
summaryMap.put("memory", Map.of(
|
||||
"avgBytes", (long) summary.avgMemory,
|
||||
"maxBytes", summary.maxMemory,
|
||||
"minBytes", summary.minMemory
|
||||
));
|
||||
summaryMap.put("disk", Map.of("maxBytes", summary.maxDisk));
|
||||
|
||||
if (summary.hasGpu) {
|
||||
summaryMap.put("gpu", Map.of(
|
||||
"avg", summary.avgGpu,
|
||||
"max", summary.maxGpu
|
||||
));
|
||||
summaryMap.put("gpuMemory", Map.of("maxBytes", summary.maxGpuMemory));
|
||||
}
|
||||
response.put("summary", summaryMap);
|
||||
|
||||
if (!summaryOnly) {
|
||||
List<Map<String, Object>> samples = new ArrayList<>();
|
||||
for (UsageRecord record : records) {
|
||||
Map<String, Object> sample = new LinkedHashMap<>();
|
||||
sample.put("timestamp", record.timestamp().toString());
|
||||
sample.put("cpuPercent", record.cpuPercent());
|
||||
sample.put("memoryBytes", record.memoryBytes());
|
||||
sample.put("diskBytes", record.diskBytes());
|
||||
if (record.gpuPercent() != null) {
|
||||
sample.put("gpuPercent", record.gpuPercent());
|
||||
}
|
||||
if (record.gpuMemoryBytes() != null) {
|
||||
sample.put("gpuMemoryBytes", record.gpuMemoryBytes());
|
||||
}
|
||||
samples.add(sample);
|
||||
}
|
||||
response.put("samples", samples);
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
private UsageSummary calculateSummary(List<UsageRecord> records) {
|
||||
if (records.isEmpty()) {
|
||||
return new UsageSummary(0, 0, 0, 0, 0, 0, 0, false, 0, 0, 0);
|
||||
}
|
||||
|
||||
double totalCpu = 0;
|
||||
double totalMemory = 0;
|
||||
double totalGpu = 0;
|
||||
int gpuCount = 0;
|
||||
|
||||
double maxCpu = 0;
|
||||
double minCpu = Double.MAX_VALUE;
|
||||
long maxMemory = 0;
|
||||
long minMemory = Long.MAX_VALUE;
|
||||
long maxDisk = 0;
|
||||
double maxGpu = 0;
|
||||
long maxGpuMemory = 0;
|
||||
|
||||
for (UsageRecord record : records) {
|
||||
totalCpu += record.cpuPercent();
|
||||
totalMemory += record.memoryBytes();
|
||||
|
||||
maxCpu = Math.max(maxCpu, record.cpuPercent());
|
||||
minCpu = Math.min(minCpu, record.cpuPercent());
|
||||
maxMemory = Math.max(maxMemory, record.memoryBytes());
|
||||
minMemory = Math.min(minMemory, record.memoryBytes());
|
||||
maxDisk = Math.max(maxDisk, record.diskBytes());
|
||||
|
||||
if (record.gpuPercent() != null) {
|
||||
totalGpu += record.gpuPercent();
|
||||
maxGpu = Math.max(maxGpu, record.gpuPercent());
|
||||
gpuCount++;
|
||||
}
|
||||
if (record.gpuMemoryBytes() != null) {
|
||||
maxGpuMemory = Math.max(maxGpuMemory, record.gpuMemoryBytes());
|
||||
}
|
||||
}
|
||||
|
||||
double avgCpu = totalCpu / records.size();
|
||||
double avgMemory = totalMemory / records.size();
|
||||
boolean hasGpu = gpuCount > 0;
|
||||
double avgGpu = hasGpu ? totalGpu / gpuCount : 0;
|
||||
|
||||
return new UsageSummary(
|
||||
avgCpu, maxCpu, minCpu,
|
||||
avgMemory, maxMemory, minMemory,
|
||||
maxDisk, hasGpu, avgGpu, maxGpu, maxGpuMemory
|
||||
);
|
||||
}
|
||||
|
||||
private record UsageSummary(
|
||||
double avgCpu,
|
||||
double maxCpu,
|
||||
double minCpu,
|
||||
double avgMemory,
|
||||
long maxMemory,
|
||||
long minMemory,
|
||||
long maxDisk,
|
||||
boolean hasGpu,
|
||||
double avgGpu,
|
||||
double maxGpu,
|
||||
long maxGpuMemory
|
||||
) { }
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
package com.samsonmedia.barn.cli;
|
||||
|
||||
import java.lang.reflect.RecordComponent;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
|
||||
/**
|
||||
* Formats output as XML.
|
||||
*
|
||||
* <p>Produces machine-readable XML with proper element naming and escaping.
|
||||
*/
|
||||
public class XmlFormatter implements OutputFormatter {
|
||||
|
||||
private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
|
||||
private static final String INDENT = " ";
|
||||
|
||||
@Override
|
||||
public String format(Object value) {
|
||||
if (value == null) {
|
||||
return XML_HEADER + "\n<null/>";
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(XML_HEADER).append("\n");
|
||||
|
||||
if (value instanceof Job job) {
|
||||
formatJob(sb, job, 0);
|
||||
} else if (value instanceof Map<?, ?> map) {
|
||||
formatMap(sb, "result", map, 0);
|
||||
} else if (value.getClass().isRecord()) {
|
||||
formatRecord(sb, value, 0);
|
||||
} else {
|
||||
sb.append("<result>").append(escapeXml(value.toString())).append("</result>");
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String formatList(List<?> values) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(XML_HEADER).append("\n");
|
||||
|
||||
if (values == null || values.isEmpty()) {
|
||||
sb.append("<results/>");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
sb.append("<results>\n");
|
||||
|
||||
for (Object value : values) {
|
||||
if (value instanceof Job job) {
|
||||
formatJob(sb, job, 1);
|
||||
} else if (value instanceof Map<?, ?> map) {
|
||||
formatMap(sb, "item", map, 1);
|
||||
} else if (value != null && value.getClass().isRecord()) {
|
||||
formatRecord(sb, value, 1);
|
||||
} else {
|
||||
sb.append(INDENT).append("<item>").append(escapeXml(String.valueOf(value)))
|
||||
.append("</item>\n");
|
||||
}
|
||||
}
|
||||
|
||||
sb.append("</results>");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
@Override
|
||||
public String formatError(String message, Throwable cause) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(XML_HEADER).append("\n");
|
||||
sb.append("<error>\n");
|
||||
sb.append(INDENT).append("<message>").append(escapeXml(message)).append("</message>\n");
|
||||
|
||||
if (cause != null) {
|
||||
sb.append(INDENT).append("<cause>").append(escapeXml(cause.getMessage()))
|
||||
.append("</cause>\n");
|
||||
sb.append(INDENT).append("<type>").append(cause.getClass().getSimpleName())
|
||||
.append("</type>\n");
|
||||
}
|
||||
|
||||
sb.append("</error>");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private void formatJob(StringBuilder sb, Job job, int depth) {
|
||||
String indent = INDENT.repeat(depth);
|
||||
String childIndent = INDENT.repeat(depth + 1);
|
||||
|
||||
sb.append(indent).append("<job>\n");
|
||||
sb.append(childIndent).append("<id>").append(escapeXml(job.id())).append("</id>\n");
|
||||
sb.append(childIndent).append("<state>").append(job.state().toString().toLowerCase())
|
||||
.append("</state>\n");
|
||||
|
||||
// Command as nested elements
|
||||
sb.append(childIndent).append("<command>\n");
|
||||
for (String arg : job.command()) {
|
||||
sb.append(childIndent).append(INDENT).append("<arg>").append(escapeXml(arg))
|
||||
.append("</arg>\n");
|
||||
}
|
||||
sb.append(childIndent).append("</command>\n");
|
||||
|
||||
if (job.tag() != null) {
|
||||
sb.append(childIndent).append("<tag>").append(escapeXml(job.tag())).append("</tag>\n");
|
||||
}
|
||||
|
||||
sb.append(childIndent).append("<created_at>").append(formatTimestamp(job.createdAt()))
|
||||
.append("</created_at>\n");
|
||||
|
||||
if (job.startedAt() != null) {
|
||||
sb.append(childIndent).append("<started_at>").append(formatTimestamp(job.startedAt()))
|
||||
.append("</started_at>\n");
|
||||
}
|
||||
|
||||
if (job.finishedAt() != null) {
|
||||
sb.append(childIndent).append("<finished_at>").append(formatTimestamp(job.finishedAt()))
|
||||
.append("</finished_at>\n");
|
||||
}
|
||||
|
||||
if (job.exitCode() != null) {
|
||||
sb.append(childIndent).append("<exit_code>").append(job.exitCode())
|
||||
.append("</exit_code>\n");
|
||||
}
|
||||
|
||||
if (job.error() != null) {
|
||||
sb.append(childIndent).append("<error>").append(escapeXml(job.error()))
|
||||
.append("</error>\n");
|
||||
}
|
||||
|
||||
if (job.pid() != null) {
|
||||
sb.append(childIndent).append("<pid>").append(job.pid()).append("</pid>\n");
|
||||
}
|
||||
|
||||
if (job.heartbeat() != null) {
|
||||
sb.append(childIndent).append("<heartbeat>").append(formatTimestamp(job.heartbeat()))
|
||||
.append("</heartbeat>\n");
|
||||
}
|
||||
|
||||
if (job.retryCount() > 0) {
|
||||
sb.append(childIndent).append("<retry_count>").append(job.retryCount())
|
||||
.append("</retry_count>\n");
|
||||
}
|
||||
|
||||
if (job.retryAt() != null) {
|
||||
sb.append(childIndent).append("<retry_at>").append(formatTimestamp(job.retryAt()))
|
||||
.append("</retry_at>\n");
|
||||
}
|
||||
|
||||
sb.append(indent).append("</job>\n");
|
||||
}
|
||||
|
||||
private void formatMap(StringBuilder sb, String elementName, Map<?, ?> map, int depth) {
|
||||
String indent = INDENT.repeat(depth);
|
||||
String childIndent = INDENT.repeat(depth + 1);
|
||||
|
||||
sb.append(indent).append("<").append(elementName).append(">\n");
|
||||
|
||||
for (Map.Entry<?, ?> entry : map.entrySet()) {
|
||||
String key = toXmlElementName(entry.getKey().toString());
|
||||
Object value = entry.getValue();
|
||||
|
||||
if (value == null) {
|
||||
sb.append(childIndent).append("<").append(key).append("/>\n");
|
||||
} else {
|
||||
sb.append(childIndent).append("<").append(key).append(">")
|
||||
.append(escapeXml(value.toString()))
|
||||
.append("</").append(key).append(">\n");
|
||||
}
|
||||
}
|
||||
|
||||
sb.append(indent).append("</").append(elementName).append(">\n");
|
||||
}
|
||||
|
||||
private void formatRecord(StringBuilder sb, Object record, int depth) {
|
||||
String indent = INDENT.repeat(depth);
|
||||
String childIndent = INDENT.repeat(depth + 1);
|
||||
String elementName = toXmlElementName(record.getClass().getSimpleName());
|
||||
|
||||
sb.append(indent).append("<").append(elementName).append(">\n");
|
||||
|
||||
for (RecordComponent component : record.getClass().getRecordComponents()) {
|
||||
try {
|
||||
Object value = component.getAccessor().invoke(record);
|
||||
String name = toXmlElementName(component.getName());
|
||||
|
||||
if (value == null) {
|
||||
sb.append(childIndent).append("<").append(name).append("/>\n");
|
||||
} else if (value instanceof List<?> list) {
|
||||
sb.append(childIndent).append("<").append(name).append(">\n");
|
||||
for (Object item : list) {
|
||||
sb.append(childIndent).append(INDENT).append("<item>")
|
||||
.append(escapeXml(item.toString())).append("</item>\n");
|
||||
}
|
||||
sb.append(childIndent).append("</").append(name).append(">\n");
|
||||
} else {
|
||||
sb.append(childIndent).append("<").append(name).append(">")
|
||||
.append(escapeXml(formatValue(value)))
|
||||
.append("</").append(name).append(">\n");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Skip fields that can't be accessed
|
||||
}
|
||||
}
|
||||
|
||||
sb.append(indent).append("</").append(elementName).append(">\n");
|
||||
}
|
||||
|
||||
private String formatValue(Object value) {
|
||||
if (value instanceof Instant instant) {
|
||||
return formatTimestamp(instant);
|
||||
}
|
||||
return value.toString();
|
||||
}
|
||||
|
||||
private String formatTimestamp(Instant timestamp) {
|
||||
if (timestamp == null) {
|
||||
return "";
|
||||
}
|
||||
return timestamp.toString();
|
||||
}
|
||||
|
||||
private String toXmlElementName(String name) {
|
||||
// Convert camelCase to snake_case for XML elements
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (int i = 0; i < name.length(); i++) {
|
||||
char c = name.charAt(i);
|
||||
if (Character.isUpperCase(c) && i > 0) {
|
||||
sb.append('_');
|
||||
}
|
||||
sb.append(Character.toLowerCase(c));
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
private String escapeXml(String text) {
|
||||
if (text == null) {
|
||||
return "";
|
||||
}
|
||||
return text
|
||||
.replace("&", "&")
|
||||
.replace("<", "<")
|
||||
.replace(">", ">")
|
||||
.replace("\"", """)
|
||||
.replace("'", "'");
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,17 @@ public final class ConfigLoader {
|
||||
return load(Optional.empty());
|
||||
}
|
||||
|
||||
/**
|
||||
* Static convenience method to load configuration from a file.
|
||||
*
|
||||
* @param path the path to the config file
|
||||
* @return the loaded configuration
|
||||
* @throws ConfigException if the file cannot be read or is invalid
|
||||
*/
|
||||
public static Config load(Path path) {
|
||||
return new ConfigLoader().loadFromFile(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads configuration, optionally with an explicit config file.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
package com.samsonmedia.barn.execution;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Recovers orphaned jobs on daemon startup.
|
||||
*
|
||||
* <p>A job is considered orphaned when:
|
||||
* <ul>
|
||||
* <li>Its state is RUNNING</li>
|
||||
* <li>Its heartbeat is stale (older than threshold)</li>
|
||||
* <li>Its process is no longer alive (or PID is unknown)</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>Orphaned jobs are marked as failed with a symbolic exit code.
|
||||
*/
|
||||
public class CrashRecovery {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CrashRecovery.class);
|
||||
private static final String ORPHANED_EXIT_CODE = "orphaned_process";
|
||||
private static final String ORPHANED_ERROR = "Process orphaned - daemon restarted";
|
||||
|
||||
private final JobRepository repository;
|
||||
private final HeartbeatChecker heartbeatChecker;
|
||||
private final BarnDirectories dirs;
|
||||
|
||||
/**
|
||||
* Creates a CrashRecovery instance.
|
||||
*
|
||||
* @param repository the job repository
|
||||
* @param heartbeatChecker the heartbeat checker
|
||||
* @param dirs the directory manager
|
||||
*/
|
||||
public CrashRecovery(JobRepository repository, HeartbeatChecker heartbeatChecker, BarnDirectories dirs) {
|
||||
this.repository = Objects.requireNonNull(repository, "repository must not be null");
|
||||
this.heartbeatChecker = Objects.requireNonNull(heartbeatChecker, "heartbeatChecker must not be null");
|
||||
this.dirs = Objects.requireNonNull(dirs, "dirs must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Scans for and recovers orphaned jobs.
|
||||
*
|
||||
* <p>This method should be called on daemon startup, before the scheduler
|
||||
* begins accepting new jobs.
|
||||
*
|
||||
* @return the list of jobs that were recovered
|
||||
* @throws IOException if scanning or recovery fails
|
||||
*/
|
||||
public List<Job> recoverOrphanedJobs() throws IOException {
|
||||
LOG.info("Scanning for orphaned jobs...");
|
||||
|
||||
List<Job> orphaned = new ArrayList<>();
|
||||
List<Job> allJobs = repository.findAll();
|
||||
|
||||
for (Job job : allJobs) {
|
||||
if (isOrphaned(job)) {
|
||||
try {
|
||||
recoverJob(job);
|
||||
orphaned.add(job);
|
||||
} catch (IOException e) {
|
||||
LOG.error("Failed to recover orphaned job {}: {}", job.id(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (orphaned.isEmpty()) {
|
||||
LOG.info("No orphaned jobs found");
|
||||
} else {
|
||||
LOG.info("Recovered {} orphaned job(s)", orphaned.size());
|
||||
}
|
||||
|
||||
return orphaned;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a job is orphaned.
|
||||
*
|
||||
* <p>A job is orphaned if it is in RUNNING state but its process
|
||||
* is no longer alive or its heartbeat is stale.
|
||||
*
|
||||
* @param job the job to check
|
||||
* @return true if the job is orphaned
|
||||
*/
|
||||
public boolean isOrphaned(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
|
||||
// Only running jobs can be orphaned
|
||||
if (job.state() != JobState.RUNNING) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check heartbeat first - if it's fresh, process might still be writing
|
||||
if (!heartbeatChecker.isStale(job)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Heartbeat is stale, verify process is actually dead
|
||||
if (job.pid() == null) {
|
||||
// No PID recorded = definitely orphaned
|
||||
LOG.debug("Job {} has no PID and stale heartbeat, marking as orphaned", job.id());
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if process is still alive
|
||||
boolean alive = ProcessUtils.isAlive(job.pid());
|
||||
if (alive) {
|
||||
// Process is alive but heartbeat is stale - could be a bug, but not orphaned
|
||||
LOG.warn("Job {} has stale heartbeat but process {} is still alive", job.id(), job.pid());
|
||||
return false;
|
||||
}
|
||||
|
||||
LOG.debug("Job {} has stale heartbeat and process {} is dead, marking as orphaned",
|
||||
job.id(), job.pid());
|
||||
return true;
|
||||
}
|
||||
|
||||
private void recoverJob(Job job) throws IOException {
|
||||
LOG.info("Recovering orphaned job: {} (PID: {})", job.id(), job.pid());
|
||||
|
||||
repository.markFailed(job.id(), ORPHANED_EXIT_CODE, ORPHANED_ERROR);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package com.samsonmedia.barn.execution;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Checks if a job's heartbeat is stale.
|
||||
*
|
||||
* <p>A job is considered to have a stale heartbeat if:
|
||||
* <ul>
|
||||
* <li>Its state is RUNNING</li>
|
||||
* <li>Its heartbeat is null or older than the threshold</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class HeartbeatChecker {
|
||||
|
||||
private final Duration threshold;
|
||||
|
||||
/**
|
||||
* Creates a HeartbeatChecker with the specified threshold.
|
||||
*
|
||||
* @param threshold the duration after which a heartbeat is considered stale
|
||||
* @throws NullPointerException if threshold is null
|
||||
* @throws IllegalArgumentException if threshold is zero or negative
|
||||
*/
|
||||
public HeartbeatChecker(Duration threshold) {
|
||||
Objects.requireNonNull(threshold, "threshold must not be null");
|
||||
if (threshold.isZero() || threshold.isNegative()) {
|
||||
throw new IllegalArgumentException("threshold must be positive");
|
||||
}
|
||||
this.threshold = threshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a job's heartbeat is stale.
|
||||
*
|
||||
* <p>Only running jobs can have stale heartbeats. Jobs in other states
|
||||
* (queued, succeeded, failed, canceled) are never considered stale.
|
||||
*
|
||||
* @param job the job to check
|
||||
* @return true if the job is running and its heartbeat is stale
|
||||
* @throws NullPointerException if job is null
|
||||
*/
|
||||
public boolean isStale(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
|
||||
// Only running jobs can be stale
|
||||
if (job.state() != JobState.RUNNING) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// No heartbeat means definitely stale
|
||||
if (job.heartbeat() == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if heartbeat is older than threshold
|
||||
Instant cutoff = Instant.now().minus(threshold);
|
||||
return job.heartbeat().isBefore(cutoff);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the stale heartbeat threshold.
|
||||
*
|
||||
* @return the threshold duration
|
||||
*/
|
||||
public Duration getThreshold() {
|
||||
return threshold;
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,11 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.jobs.RetryCalculator;
|
||||
import com.samsonmedia.barn.monitoring.UsageMonitor;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
|
||||
/**
|
||||
@@ -36,6 +39,7 @@ public class JobRunner {
|
||||
private final ProcessMonitor monitor;
|
||||
private final JobRepository repository;
|
||||
private final BarnDirectories dirs;
|
||||
private final RetryCalculator retryCalculator;
|
||||
|
||||
/**
|
||||
* Creates a JobRunner.
|
||||
@@ -44,16 +48,19 @@ public class JobRunner {
|
||||
* @param monitor the process monitor
|
||||
* @param repository the job repository
|
||||
* @param dirs the directory manager
|
||||
* @param retryCalculator the retry calculator
|
||||
*/
|
||||
public JobRunner(
|
||||
ProcessExecutor executor,
|
||||
ProcessMonitor monitor,
|
||||
JobRepository repository,
|
||||
BarnDirectories dirs) {
|
||||
BarnDirectories dirs,
|
||||
RetryCalculator retryCalculator) {
|
||||
this.executor = Objects.requireNonNull(executor, "executor must not be null");
|
||||
this.monitor = Objects.requireNonNull(monitor, "monitor must not be null");
|
||||
this.repository = Objects.requireNonNull(repository, "repository must not be null");
|
||||
this.dirs = Objects.requireNonNull(dirs, "dirs must not be null");
|
||||
this.retryCalculator = retryCalculator; // May be null to disable retries
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,7 +70,19 @@ public class JobRunner {
|
||||
* @param dirs the directory manager
|
||||
*/
|
||||
public JobRunner(JobRepository repository, BarnDirectories dirs) {
|
||||
this(new ProcessExecutor(), new ProcessMonitor(), repository, dirs);
|
||||
this(new ProcessExecutor(), new ProcessMonitor(), repository, dirs, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a JobRunner with default executor, monitor, and retry support.
|
||||
*
|
||||
* @param repository the job repository
|
||||
* @param dirs the directory manager
|
||||
* @param jobsConfig the jobs configuration for retry settings
|
||||
*/
|
||||
public JobRunner(JobRepository repository, BarnDirectories dirs, JobsConfig jobsConfig) {
|
||||
this(new ProcessExecutor(), new ProcessMonitor(), repository, dirs,
|
||||
jobsConfig != null ? new RetryCalculator(jobsConfig) : null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -101,23 +120,46 @@ public class JobRunner {
|
||||
// Update state to RUNNING
|
||||
repository.markStarted(job.id(), pid);
|
||||
|
||||
// Monitor the process with heartbeat updates
|
||||
ProcessMonitor.ProcessEvent.Completed completedEvent = monitor.monitorBlocking(
|
||||
process,
|
||||
event -> handleEvent(job.id(), event)
|
||||
);
|
||||
// Start usage monitoring
|
||||
UsageMonitor usageMonitor = new UsageMonitor(pid, workDir, logsDir);
|
||||
usageMonitor.start();
|
||||
|
||||
completed.set(true);
|
||||
try {
|
||||
// Monitor the process with heartbeat updates
|
||||
ProcessMonitor.ProcessEvent.Completed completedEvent = monitor.monitorBlocking(
|
||||
process,
|
||||
event -> handleEvent(job.id(), event)
|
||||
);
|
||||
|
||||
// Update final state
|
||||
int exitCode = completedEvent.exitCode();
|
||||
String error = exitCode == 0 ? null : "Process exited with code " + exitCode;
|
||||
repository.markCompleted(job.id(), exitCode, error);
|
||||
completed.set(true);
|
||||
|
||||
Duration duration = Duration.between(startTime, Instant.now());
|
||||
LOG.info("Job {} completed with exit code {} in {}", job.id(), exitCode, formatDuration(duration));
|
||||
// Update final state
|
||||
int exitCode = completedEvent.exitCode();
|
||||
String error = exitCode == 0 ? null : "Process exited with code " + exitCode;
|
||||
|
||||
return new JobResult(exitCode, duration, error);
|
||||
// Check if we should retry
|
||||
if (exitCode != 0 && shouldRetry(job, exitCode)) {
|
||||
handleRetry(job, exitCode, error);
|
||||
Duration duration = Duration.between(startTime, Instant.now());
|
||||
LOG.info("Job {} failed with exit code {} and scheduled for retry in {}",
|
||||
job.id(), exitCode, formatDuration(duration));
|
||||
return new JobResult(exitCode, duration, error, true);
|
||||
}
|
||||
|
||||
repository.markCompleted(job.id(), exitCode, error);
|
||||
|
||||
Duration duration = Duration.between(startTime, Instant.now());
|
||||
LOG.info("Job {} completed with exit code {} in {}", job.id(), exitCode, formatDuration(duration));
|
||||
|
||||
return new JobResult(exitCode, duration, error, false);
|
||||
} finally {
|
||||
// Always stop and close usage monitoring
|
||||
try {
|
||||
usageMonitor.close();
|
||||
} catch (IOException e) {
|
||||
LOG.warn("Failed to close usage monitor for job {}: {}", job.id(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
LOG.error("Failed to start job {}: {}", job.id(), e.getMessage(), e);
|
||||
@@ -131,7 +173,7 @@ public class JobRunner {
|
||||
}
|
||||
|
||||
Duration duration = Duration.between(startTime, Instant.now());
|
||||
return new JobResult(-1, duration, e.getMessage());
|
||||
return new JobResult(-1, duration, e.getMessage(), false);
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
@@ -146,10 +188,31 @@ public class JobRunner {
|
||||
}
|
||||
|
||||
Duration duration = Duration.between(startTime, Instant.now());
|
||||
return new JobResult(-1, duration, "Job was interrupted");
|
||||
return new JobResult(-1, duration, "Job was interrupted", false);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldRetry(Job job, int exitCode) {
|
||||
if (retryCalculator == null) {
|
||||
return false;
|
||||
}
|
||||
// Create a temporary job with the exit code to check retry eligibility
|
||||
Job jobWithExitCode = new Job(
|
||||
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()
|
||||
);
|
||||
return retryCalculator.shouldRetry(jobWithExitCode);
|
||||
}
|
||||
|
||||
private void handleRetry(Job job, int exitCode, String error) throws IOException {
|
||||
Instant retryAt = retryCalculator.calculateRetryAt(job);
|
||||
repository.scheduleRetry(job.id(), retryAt, exitCode, error);
|
||||
LOG.info("Job {} retry {} of {} scheduled for {}",
|
||||
job.id(), job.retryCount() + 1, retryCalculator.getMaxRetries(), retryAt);
|
||||
}
|
||||
|
||||
private void handleEvent(String jobId, ProcessMonitor.ProcessEvent event) {
|
||||
try {
|
||||
switch (event) {
|
||||
@@ -189,14 +252,37 @@ public class JobRunner {
|
||||
* @param exitCode the process exit code (-1 if process failed to start)
|
||||
* @param duration the total runtime
|
||||
* @param error the error message, if any
|
||||
* @param retryScheduled true if a retry was scheduled
|
||||
*/
|
||||
public record JobResult(int exitCode, Duration duration, String error) {
|
||||
public record JobResult(int exitCode, Duration duration, String error, boolean retryScheduled) {
|
||||
|
||||
/**
|
||||
* Creates a JobResult without retry information (defaults to false).
|
||||
*
|
||||
* @param exitCode the process exit code
|
||||
* @param duration the total runtime
|
||||
* @param error the error message, if any
|
||||
*/
|
||||
public JobResult(int exitCode, Duration duration, String error) {
|
||||
this(exitCode, duration, error, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the job completed successfully.
|
||||
*
|
||||
* @return true if exit code is 0
|
||||
*/
|
||||
public boolean isSuccess() {
|
||||
return exitCode == 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if the job failed but a retry was scheduled.
|
||||
*
|
||||
* @return true if a retry is pending
|
||||
*/
|
||||
public boolean isRetryPending() {
|
||||
return !isSuccess() && retryScheduled;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,329 @@
|
||||
package com.samsonmedia.barn.execution;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.Config;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.BarnDirectories;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Scheduler for managing concurrent job execution.
|
||||
*
|
||||
* <p>The scheduler polls for queued jobs and executes them respecting
|
||||
* the configured maximum concurrent jobs limit.
|
||||
*/
|
||||
public class JobScheduler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JobScheduler.class);
|
||||
private static final Duration DEFAULT_POLL_INTERVAL = Duration.ofSeconds(1);
|
||||
private static final Duration DEFAULT_SHUTDOWN_TIMEOUT = Duration.ofMinutes(5);
|
||||
|
||||
private final JobRepository repository;
|
||||
private final JobRunner runner;
|
||||
private final BarnDirectories dirs;
|
||||
private final int maxConcurrentJobs;
|
||||
private final Duration pollInterval;
|
||||
private final Duration shutdownTimeout;
|
||||
|
||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||
private final AtomicInteger runningJobCount = new AtomicInteger(0);
|
||||
|
||||
private ExecutorService jobExecutor;
|
||||
private ScheduledExecutorService schedulerThread;
|
||||
private SchedulerLock lock;
|
||||
|
||||
/**
|
||||
* Creates a JobScheduler with the specified configuration.
|
||||
*
|
||||
* @param repository the job repository
|
||||
* @param runner the job runner
|
||||
* @param dirs the directory manager
|
||||
* @param config the configuration
|
||||
*/
|
||||
public JobScheduler(
|
||||
JobRepository repository,
|
||||
JobRunner runner,
|
||||
BarnDirectories dirs,
|
||||
Config config) {
|
||||
this(repository, runner, dirs,
|
||||
config.service().maxConcurrentJobs(),
|
||||
DEFAULT_POLL_INTERVAL,
|
||||
DEFAULT_SHUTDOWN_TIMEOUT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a JobScheduler with custom settings.
|
||||
*
|
||||
* @param repository the job repository
|
||||
* @param runner the job runner
|
||||
* @param dirs the directory manager
|
||||
* @param maxConcurrentJobs the maximum number of concurrent jobs
|
||||
* @param pollInterval the interval between queue checks
|
||||
* @param shutdownTimeout the maximum time to wait for shutdown
|
||||
*/
|
||||
public JobScheduler(
|
||||
JobRepository repository,
|
||||
JobRunner runner,
|
||||
BarnDirectories dirs,
|
||||
int maxConcurrentJobs,
|
||||
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.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);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the scheduler.
|
||||
*
|
||||
* <p>Acquires the scheduler lock and begins processing queued jobs.
|
||||
*
|
||||
* @throws IllegalStateException if already running or lock cannot be acquired
|
||||
* @throws IOException if lock acquisition fails
|
||||
*/
|
||||
public void start() throws IOException {
|
||||
if (running.get()) {
|
||||
throw new IllegalStateException("Scheduler is already running");
|
||||
}
|
||||
|
||||
// Acquire lock
|
||||
Optional<SchedulerLock> acquired = SchedulerLock.tryAcquire(dirs.getSchedulerLockFile());
|
||||
if (acquired.isEmpty()) {
|
||||
throw new IllegalStateException("Another scheduler is already running");
|
||||
}
|
||||
lock = acquired.get();
|
||||
|
||||
// Create executors
|
||||
jobExecutor = Executors.newFixedThreadPool(maxConcurrentJobs, r -> {
|
||||
Thread t = new Thread(r, "job-executor");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
schedulerThread = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "job-scheduler");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
running.set(true);
|
||||
|
||||
// Start the scheduling loop
|
||||
schedulerThread.scheduleAtFixedRate(
|
||||
this::scheduleNextJob,
|
||||
0,
|
||||
pollInterval.toMillis(),
|
||||
TimeUnit.MILLISECONDS
|
||||
);
|
||||
|
||||
LOG.info("Scheduler started with max {} concurrent jobs", maxConcurrentJobs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the scheduler gracefully.
|
||||
*
|
||||
* <p>Waits for running jobs to complete up to the shutdown timeout.
|
||||
*/
|
||||
public void stop() {
|
||||
if (!running.compareAndSet(true, false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
LOG.info("Stopping scheduler gracefully...");
|
||||
|
||||
// Stop scheduling new jobs
|
||||
if (schedulerThread != null) {
|
||||
schedulerThread.shutdown();
|
||||
}
|
||||
|
||||
// Wait for running jobs
|
||||
if (jobExecutor != null) {
|
||||
jobExecutor.shutdown();
|
||||
try {
|
||||
if (!jobExecutor.awaitTermination(shutdownTimeout.toMillis(), TimeUnit.MILLISECONDS)) {
|
||||
LOG.warn("Timeout waiting for jobs, forcing shutdown");
|
||||
jobExecutor.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
jobExecutor.shutdownNow();
|
||||
}
|
||||
}
|
||||
|
||||
// Release lock
|
||||
if (lock != null) {
|
||||
lock.close();
|
||||
lock = null;
|
||||
}
|
||||
|
||||
LOG.info("Scheduler stopped");
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the scheduler immediately.
|
||||
*
|
||||
* <p>Kills any running jobs without waiting.
|
||||
*/
|
||||
public void stopNow() {
|
||||
if (!running.compareAndSet(true, false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
LOG.info("Stopping scheduler immediately...");
|
||||
|
||||
// Kill everything
|
||||
if (schedulerThread != null) {
|
||||
schedulerThread.shutdownNow();
|
||||
}
|
||||
|
||||
if (jobExecutor != null) {
|
||||
jobExecutor.shutdownNow();
|
||||
}
|
||||
|
||||
// Release lock
|
||||
if (lock != null) {
|
||||
lock.close();
|
||||
lock = null;
|
||||
}
|
||||
|
||||
LOG.info("Scheduler stopped");
|
||||
}
|
||||
|
||||
/**
|
||||
* Submits a job for execution.
|
||||
*
|
||||
* <p>The job will be picked up by the scheduler in FIFO order.
|
||||
*
|
||||
* @param job the job to submit
|
||||
*/
|
||||
public void submit(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
// Jobs are already in the repository with QUEUED state
|
||||
// The scheduler will pick them up in the next poll
|
||||
LOG.debug("Job submitted for scheduling: {}", job.id());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current scheduler status.
|
||||
*
|
||||
* @return the scheduler status
|
||||
*/
|
||||
public SchedulerStatus getStatus() {
|
||||
int queuedCount = 0;
|
||||
try {
|
||||
queuedCount = repository.findByState(JobState.QUEUED).size();
|
||||
} catch (IOException e) {
|
||||
LOG.warn("Failed to count queued jobs: {}", e.getMessage());
|
||||
}
|
||||
|
||||
return new SchedulerStatus(
|
||||
runningJobCount.get(),
|
||||
queuedCount,
|
||||
maxConcurrentJobs,
|
||||
running.get()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the scheduler is running.
|
||||
*
|
||||
* @return true if running
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
return running.get();
|
||||
}
|
||||
|
||||
private void scheduleNextJob() {
|
||||
if (!running.get()) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if we have capacity
|
||||
int currentRunning = runningJobCount.get();
|
||||
if (currentRunning >= maxConcurrentJobs) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Find next queued job
|
||||
Optional<Job> nextJob = findNextQueued();
|
||||
if (nextJob.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Job job = nextJob.get();
|
||||
|
||||
// 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();
|
||||
|
||||
jobExecutor.submit(() -> {
|
||||
try {
|
||||
runner.run(job);
|
||||
} finally {
|
||||
runningJobCount.decrementAndGet();
|
||||
}
|
||||
});
|
||||
|
||||
LOG.debug("Scheduled job: {}", job.id());
|
||||
|
||||
} catch (IOException e) {
|
||||
LOG.error("Error in scheduler: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<Job> findNextQueued() throws IOException {
|
||||
List<Job> queuedJobs = repository.findByState(JobState.QUEUED);
|
||||
|
||||
// Sort by creation time (FIFO)
|
||||
return queuedJobs.stream()
|
||||
.filter(job -> job.retryAt() == null || !job.retryAt().isAfter(Instant.now()))
|
||||
.min(Comparator.comparing(Job::createdAt));
|
||||
}
|
||||
|
||||
/**
|
||||
* Status of the job scheduler.
|
||||
*
|
||||
* @param runningJobs the number of currently running jobs
|
||||
* @param queuedJobs the number of queued jobs
|
||||
* @param maxConcurrentJobs the maximum concurrent job limit
|
||||
* @param isRunning whether the scheduler is running
|
||||
*/
|
||||
public record SchedulerStatus(
|
||||
int runningJobs,
|
||||
int queuedJobs,
|
||||
int maxConcurrentJobs,
|
||||
boolean isRunning
|
||||
) { }
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
package com.samsonmedia.barn.execution;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.nio.channels.FileChannel;
|
||||
import java.nio.channels.OverlappingFileLockException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Lock to ensure only one scheduler runs at a time.
|
||||
*
|
||||
* <p>Uses file-based locking to prevent multiple scheduler instances.
|
||||
* The lock is held for the lifetime of this object and released when closed.
|
||||
*/
|
||||
public final class SchedulerLock implements Closeable {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SchedulerLock.class);
|
||||
|
||||
private final Path lockFile;
|
||||
private final FileChannel channel;
|
||||
private final java.nio.channels.FileLock lock;
|
||||
|
||||
private SchedulerLock(Path lockFile, FileChannel channel, java.nio.channels.FileLock lock) {
|
||||
this.lockFile = lockFile;
|
||||
this.channel = channel;
|
||||
this.lock = lock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to acquire the scheduler lock.
|
||||
*
|
||||
* @param lockFile the lock file path
|
||||
* @return the lock if acquired, or empty if already held
|
||||
* @throws IOException if lock acquisition fails for reasons other than contention
|
||||
*/
|
||||
public static Optional<SchedulerLock> tryAcquire(Path lockFile) throws IOException {
|
||||
Objects.requireNonNull(lockFile, "lockFile must not be null");
|
||||
|
||||
// Ensure parent directory exists
|
||||
Path parent = lockFile.getParent();
|
||||
if (parent != null && !Files.exists(parent)) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
|
||||
FileChannel channel = FileChannel.open(
|
||||
lockFile,
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.WRITE
|
||||
);
|
||||
|
||||
try {
|
||||
java.nio.channels.FileLock lock = channel.tryLock();
|
||||
|
||||
if (lock == null) {
|
||||
// Lock is held by another process
|
||||
channel.close();
|
||||
LOG.debug("Scheduler lock already held: {}", lockFile);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
LOG.info("Acquired scheduler lock: {}", lockFile);
|
||||
return Optional.of(new SchedulerLock(lockFile, channel, lock));
|
||||
|
||||
} catch (OverlappingFileLockException e) {
|
||||
// Lock is held by another thread in the same JVM
|
||||
channel.close();
|
||||
LOG.debug("Scheduler lock held by same JVM: {}", lockFile);
|
||||
return Optional.empty();
|
||||
} catch (IOException e) {
|
||||
channel.close();
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the lock file path.
|
||||
*
|
||||
* @return the lock file path
|
||||
*/
|
||||
public Path getLockFile() {
|
||||
return lockFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the lock is still valid.
|
||||
*
|
||||
* @return true if the lock is valid
|
||||
*/
|
||||
public boolean isValid() {
|
||||
return lock != null && lock.isValid();
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the lock.
|
||||
*/
|
||||
@Override
|
||||
public void close() {
|
||||
try {
|
||||
if (lock != null && lock.isValid()) {
|
||||
lock.release();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.warn("Error releasing scheduler lock: {}", e.getMessage());
|
||||
}
|
||||
|
||||
try {
|
||||
if (channel != null && channel.isOpen()) {
|
||||
channel.close();
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.warn("Error closing scheduler lock channel: {}", e.getMessage());
|
||||
}
|
||||
|
||||
LOG.info("Released scheduler lock: {}", lockFile);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.StandardProtocolFamily;
|
||||
import java.net.UnixDomainSocketAddress;
|
||||
import java.nio.channels.Channels;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
/**
|
||||
* IPC client for communicating with the barn service.
|
||||
*
|
||||
* <p>Uses Unix domain sockets on Linux/macOS and can fall back to
|
||||
* localhost TCP on platforms that don't support Unix sockets.
|
||||
*/
|
||||
public class IpcClient implements AutoCloseable {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(IpcClient.class);
|
||||
private static final int DEFAULT_TIMEOUT_MS = 30000;
|
||||
|
||||
private final Path socketPath;
|
||||
private final ObjectMapper objectMapper;
|
||||
private SocketChannel channel;
|
||||
|
||||
/**
|
||||
* Creates an IPC client for the given socket path.
|
||||
*
|
||||
* @param socketPath the Unix socket path
|
||||
*/
|
||||
public IpcClient(Path socketPath) {
|
||||
this.socketPath = Objects.requireNonNull(socketPath, "socketPath must not be null");
|
||||
this.objectMapper = createObjectMapper();
|
||||
}
|
||||
|
||||
private static ObjectMapper createObjectMapper() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
return mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends a request and waits for a response.
|
||||
*
|
||||
* @param <T> the expected response payload type
|
||||
* @param type the request type
|
||||
* @param payload the request payload
|
||||
* @param responseType the response payload class
|
||||
* @return the response payload
|
||||
* @throws IpcException if the request fails
|
||||
*/
|
||||
public <T> T send(String type, Object payload, Class<T> responseType) throws IpcException {
|
||||
try {
|
||||
ensureConnected();
|
||||
|
||||
// Build and send request
|
||||
IpcMessage request = IpcMessage.request(type, payload);
|
||||
String requestJson = objectMapper.writeValueAsString(request);
|
||||
LOG.debug("Sending IPC request: {}", requestJson);
|
||||
|
||||
PrintWriter writer = new PrintWriter(
|
||||
new OutputStreamWriter(Channels.newOutputStream(channel), StandardCharsets.UTF_8),
|
||||
true
|
||||
);
|
||||
writer.println(requestJson);
|
||||
|
||||
// Read response
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(Channels.newInputStream(channel), StandardCharsets.UTF_8)
|
||||
);
|
||||
String responseLine = reader.readLine();
|
||||
if (responseLine == null) {
|
||||
throw new IpcException(IpcErrorCode.CONNECTION_FAILED, "Connection closed by server");
|
||||
}
|
||||
LOG.debug("Received IPC response: {}", responseLine);
|
||||
|
||||
// Parse response
|
||||
IpcMessage response = objectMapper.readValue(responseLine, IpcMessage.class);
|
||||
|
||||
if (response.isError()) {
|
||||
throw new IpcException(response.getErrorCode(), response.getErrorMessage());
|
||||
}
|
||||
|
||||
// Convert payload to expected type
|
||||
if (response.getPayload() == null) {
|
||||
return null;
|
||||
}
|
||||
return objectMapper.convertValue(response.getPayload(), responseType);
|
||||
|
||||
} catch (IOException e) {
|
||||
throw new IpcException(IpcErrorCode.CONNECTION_FAILED, "IPC communication failed: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the service is running and accessible.
|
||||
*
|
||||
* @return true if the service is running
|
||||
*/
|
||||
public boolean isServiceRunning() {
|
||||
try {
|
||||
if (!Files.exists(socketPath)) {
|
||||
return false;
|
||||
}
|
||||
ensureConnected();
|
||||
return true;
|
||||
} catch (IpcException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the client is connected to the service.
|
||||
*
|
||||
* @throws IpcException if connection fails
|
||||
*/
|
||||
public void ensureConnected() throws IpcException {
|
||||
if (channel != null && channel.isConnected()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Files.exists(socketPath)) {
|
||||
throw new IpcException(IpcErrorCode.SERVICE_NOT_RUNNING,
|
||||
"Service not running (socket not found: " + socketPath + ")");
|
||||
}
|
||||
|
||||
try {
|
||||
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath);
|
||||
channel = SocketChannel.open(StandardProtocolFamily.UNIX);
|
||||
channel.connect(address);
|
||||
LOG.debug("Connected to IPC socket: {}", socketPath);
|
||||
} catch (IOException e) {
|
||||
throw new IpcException(IpcErrorCode.CONNECTION_FAILED,
|
||||
"Failed to connect to service: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the socket path.
|
||||
*
|
||||
* @return the socket path
|
||||
*/
|
||||
public Path getSocketPath() {
|
||||
return socketPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (channel != null) {
|
||||
try {
|
||||
channel.close();
|
||||
LOG.debug("Closed IPC connection");
|
||||
} catch (IOException e) {
|
||||
LOG.warn("Error closing IPC connection: {}", e.getMessage());
|
||||
}
|
||||
channel = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the default socket path for the current platform.
|
||||
*
|
||||
* @return the default socket path
|
||||
*/
|
||||
public static Path getDefaultSocketPath() {
|
||||
String os = System.getProperty("os.name").toLowerCase();
|
||||
if (os.contains("win")) {
|
||||
// Windows - use temp directory (named pipes require JNI)
|
||||
return Path.of(System.getProperty("java.io.tmpdir"), "barn", "barn.sock");
|
||||
}
|
||||
// Unix-like systems
|
||||
return Path.of("/tmp", "barn", "barn.sock");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
/**
|
||||
* Error codes for IPC responses.
|
||||
*/
|
||||
public final class IpcErrorCode {
|
||||
|
||||
/** Service is not running. */
|
||||
public static final String SERVICE_NOT_RUNNING = "SERVICE_NOT_RUNNING";
|
||||
|
||||
/** Job ID doesn't exist. */
|
||||
public static final String JOB_NOT_FOUND = "JOB_NOT_FOUND";
|
||||
|
||||
/** Malformed request. */
|
||||
public static final String INVALID_REQUEST = "INVALID_REQUEST";
|
||||
|
||||
/** Unexpected server error. */
|
||||
public static final String INTERNAL_ERROR = "INTERNAL_ERROR";
|
||||
|
||||
/** Job is not in running state. */
|
||||
public static final String JOB_NOT_RUNNING = "JOB_NOT_RUNNING";
|
||||
|
||||
/** Connection to service failed. */
|
||||
public static final String CONNECTION_FAILED = "CONNECTION_FAILED";
|
||||
|
||||
/** Request timed out. */
|
||||
public static final String TIMEOUT = "TIMEOUT";
|
||||
|
||||
private IpcErrorCode() {
|
||||
// Constants class - prevent instantiation
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Exception thrown when IPC operations fail.
|
||||
*/
|
||||
public class IpcException extends Exception {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private final String code;
|
||||
|
||||
/**
|
||||
* Creates an IPC exception with the given error code and message.
|
||||
*
|
||||
* @param code the error code
|
||||
* @param message the error message
|
||||
*/
|
||||
public IpcException(String code, String message) {
|
||||
super(message);
|
||||
this.code = Objects.requireNonNull(code, "code must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an IPC exception with the given error code, message, and cause.
|
||||
*
|
||||
* @param code the error code
|
||||
* @param message the error message
|
||||
* @param cause the underlying cause
|
||||
*/
|
||||
public IpcException(String code, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.code = Objects.requireNonNull(code, "code must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the error code.
|
||||
*
|
||||
* @return the error code
|
||||
*/
|
||||
public String getCode() {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
|
||||
/**
|
||||
* Wrapper class for IPC messages (both requests and responses).
|
||||
*
|
||||
* <p>The JSON format is:
|
||||
* <pre>
|
||||
* {
|
||||
* "type": "run_job",
|
||||
* "payload": { ... }
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>For responses:
|
||||
* <pre>
|
||||
* {
|
||||
* "status": "ok",
|
||||
* "payload": { ... }
|
||||
* }
|
||||
* </pre>
|
||||
*
|
||||
* <p>Or for errors:
|
||||
* <pre>
|
||||
* {
|
||||
* "status": "error",
|
||||
* "error": { "code": "...", "message": "..." }
|
||||
* }
|
||||
* </pre>
|
||||
*/
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
public final class IpcMessage {
|
||||
|
||||
private String type;
|
||||
private String status;
|
||||
private Object payload;
|
||||
@JsonProperty("error")
|
||||
private Map<String, String> error;
|
||||
|
||||
/**
|
||||
* Default constructor for JSON deserialization.
|
||||
*/
|
||||
public IpcMessage() {
|
||||
// For Jackson deserialization
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a request message.
|
||||
*
|
||||
* @param type the request type
|
||||
* @param payload the request payload
|
||||
*/
|
||||
private IpcMessage(String type, Object payload) {
|
||||
this.type = Objects.requireNonNull(type);
|
||||
this.payload = payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a response message.
|
||||
*
|
||||
* @param status the response status
|
||||
* @param payload the response payload
|
||||
* @param error the error details (for error responses)
|
||||
*/
|
||||
private IpcMessage(String status, Object payload, Map<String, String> error) {
|
||||
this.status = Objects.requireNonNull(status);
|
||||
this.payload = payload;
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a request message.
|
||||
*
|
||||
* @param type the request type
|
||||
* @param payload the request payload
|
||||
* @return the message
|
||||
*/
|
||||
public static IpcMessage request(String type, Object payload) {
|
||||
return new IpcMessage(type, payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a successful response message.
|
||||
*
|
||||
* @param payload the response payload
|
||||
* @return the message
|
||||
*/
|
||||
public static IpcMessage okResponse(Object payload) {
|
||||
return new IpcMessage("ok", payload, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an error response message.
|
||||
*
|
||||
* @param code the error code
|
||||
* @param message the error message
|
||||
* @return the message
|
||||
*/
|
||||
public static IpcMessage errorResponse(String code, String message) {
|
||||
IpcMessage msg = new IpcMessage();
|
||||
msg.status = "error";
|
||||
msg.error = Map.of("code", code, "message", message);
|
||||
return msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the request type (for request messages).
|
||||
*
|
||||
* @return the type
|
||||
*/
|
||||
public String getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the request type.
|
||||
*
|
||||
* @param type the type
|
||||
*/
|
||||
public void setType(String type) {
|
||||
this.type = type;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the response status (for response messages).
|
||||
*
|
||||
* @return the status
|
||||
*/
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the response status.
|
||||
*
|
||||
* @param status the status
|
||||
*/
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the payload.
|
||||
*
|
||||
* @return the payload
|
||||
*/
|
||||
public Object getPayload() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the payload.
|
||||
*
|
||||
* @param payload the payload
|
||||
*/
|
||||
public void setPayload(Object payload) {
|
||||
this.payload = payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the error details (for error responses).
|
||||
*
|
||||
* @return the error details
|
||||
*/
|
||||
public Map<String, String> getError() {
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the error details.
|
||||
*
|
||||
* @param error the error details
|
||||
*/
|
||||
public void setError(Map<String, String> error) {
|
||||
this.error = error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if this is a successful response.
|
||||
*
|
||||
* @return true if status is "ok"
|
||||
*/
|
||||
@JsonIgnore
|
||||
public boolean isOk() {
|
||||
return "ok".equals(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if this is an error response.
|
||||
*
|
||||
* @return true if status is "error"
|
||||
*/
|
||||
@JsonIgnore
|
||||
public boolean isError() {
|
||||
return "error".equals(status);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the error code (for error responses).
|
||||
*
|
||||
* @return the error code, or null if not an error
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getErrorCode() {
|
||||
return error != null ? error.get("code") : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the error message (for error responses).
|
||||
*
|
||||
* @return the error message, or null if not an error
|
||||
*/
|
||||
@JsonIgnore
|
||||
public String getErrorMessage() {
|
||||
return error != null ? error.get("message") : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Sealed interface for IPC requests from CLI to service.
|
||||
*/
|
||||
public sealed interface IpcRequest {
|
||||
|
||||
/**
|
||||
* Request to run a new job.
|
||||
*
|
||||
* @param command the command and arguments
|
||||
* @param tag optional user-defined tag
|
||||
* @param maxRetries maximum retry attempts
|
||||
* @param retryDelaySeconds initial retry delay
|
||||
*/
|
||||
record RunJob(
|
||||
List<String> command,
|
||||
String tag,
|
||||
int maxRetries,
|
||||
int retryDelaySeconds
|
||||
) implements IpcRequest { }
|
||||
|
||||
/**
|
||||
* Request to get job status list.
|
||||
*
|
||||
* @param tag filter by tag (null for all)
|
||||
* @param state filter by state (null for all)
|
||||
* @param limit maximum number of results (null for all)
|
||||
*/
|
||||
record GetStatus(
|
||||
String tag,
|
||||
String state,
|
||||
Integer limit
|
||||
) implements IpcRequest { }
|
||||
|
||||
/**
|
||||
* Request to get detailed job information.
|
||||
*
|
||||
* @param jobId the job ID
|
||||
* @param includeLogs whether to include log content
|
||||
* @param includeManifest whether to include manifest details
|
||||
*/
|
||||
record GetJob(
|
||||
String jobId,
|
||||
boolean includeLogs,
|
||||
boolean includeManifest
|
||||
) implements IpcRequest { }
|
||||
|
||||
/**
|
||||
* Request to kill a running job.
|
||||
*
|
||||
* @param jobId the job ID
|
||||
* @param force whether to force kill (SIGKILL)
|
||||
*/
|
||||
record KillJob(
|
||||
String jobId,
|
||||
boolean force
|
||||
) implements IpcRequest { }
|
||||
|
||||
/**
|
||||
* Request to clean completed jobs.
|
||||
*
|
||||
* @param all remove all completed jobs regardless of age
|
||||
* @param olderThan duration string (e.g., "24h")
|
||||
* @param includeFailed include failed jobs
|
||||
* @param jobId specific job to clean (null for all matching)
|
||||
* @param dryRun show what would be cleaned without removing
|
||||
*/
|
||||
record CleanJobs(
|
||||
boolean all,
|
||||
String olderThan,
|
||||
boolean includeFailed,
|
||||
String jobId,
|
||||
boolean dryRun
|
||||
) implements IpcRequest { }
|
||||
|
||||
/**
|
||||
* Request to get service status.
|
||||
*/
|
||||
record GetServiceStatus() implements IpcRequest { }
|
||||
|
||||
/**
|
||||
* Request to shutdown the service.
|
||||
*/
|
||||
record Shutdown() implements IpcRequest { }
|
||||
|
||||
/**
|
||||
* Request to reload configuration.
|
||||
*/
|
||||
record Reload() implements IpcRequest { }
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
/**
|
||||
* Sealed interface for IPC responses from service to CLI.
|
||||
*
|
||||
* @param <T> the payload type for success responses
|
||||
*/
|
||||
public sealed interface IpcResponse<T> {
|
||||
|
||||
/**
|
||||
* Successful response with payload.
|
||||
*
|
||||
* @param <T> the payload type
|
||||
* @param payload the response data
|
||||
*/
|
||||
record Ok<T>(T payload) implements IpcResponse<T> { }
|
||||
|
||||
/**
|
||||
* Error response.
|
||||
*
|
||||
* @param <T> unused type parameter for compatibility
|
||||
* @param code the error code
|
||||
* @param message the error message
|
||||
*/
|
||||
record Error<T>(String code, String message) implements IpcResponse<T> { }
|
||||
|
||||
/**
|
||||
* Creates a successful response with the given payload.
|
||||
*
|
||||
* @param <T> the payload type
|
||||
* @param payload the response data
|
||||
* @return a successful response
|
||||
*/
|
||||
static <T> IpcResponse<T> ok(T payload) {
|
||||
return new Ok<>(payload);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an error response.
|
||||
*
|
||||
* @param <T> unused type parameter
|
||||
* @param code the error code
|
||||
* @param message the error message
|
||||
* @return an error response
|
||||
*/
|
||||
static <T> IpcResponse<T> error(String code, String message) {
|
||||
return new Error<>(code, message);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
package com.samsonmedia.barn.ipc;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStreamWriter;
|
||||
import java.io.PrintWriter;
|
||||
import java.net.StandardProtocolFamily;
|
||||
import java.net.UnixDomainSocketAddress;
|
||||
import java.nio.channels.Channels;
|
||||
import java.nio.channels.ServerSocketChannel;
|
||||
import java.nio.channels.SocketChannel;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
/**
|
||||
* IPC server for receiving requests from CLI clients.
|
||||
*
|
||||
* <p>Uses Unix domain sockets on Linux/macOS.
|
||||
*/
|
||||
public class IpcServer {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(IpcServer.class);
|
||||
|
||||
private final Path socketPath;
|
||||
private final RequestHandler handler;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final AtomicBoolean running;
|
||||
private final ExecutorService executor;
|
||||
private ServerSocketChannel serverChannel;
|
||||
|
||||
/**
|
||||
* Creates an IPC server.
|
||||
*
|
||||
* @param socketPath the Unix socket path
|
||||
* @param handler the request handler
|
||||
*/
|
||||
public IpcServer(Path socketPath, RequestHandler handler) {
|
||||
this.socketPath = Objects.requireNonNull(socketPath, "socketPath must not be null");
|
||||
this.handler = Objects.requireNonNull(handler, "handler must not be null");
|
||||
this.objectMapper = createObjectMapper();
|
||||
this.running = new AtomicBoolean(false);
|
||||
this.executor = Executors.newCachedThreadPool(r -> {
|
||||
Thread t = new Thread(r, "ipc-handler");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
}
|
||||
|
||||
private static ObjectMapper createObjectMapper() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
return mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the IPC server.
|
||||
*
|
||||
* @throws IOException if starting fails
|
||||
*/
|
||||
public void start() throws IOException {
|
||||
if (running.getAndSet(true)) {
|
||||
throw new IllegalStateException("Server already running");
|
||||
}
|
||||
|
||||
// Clean up existing socket file
|
||||
Files.deleteIfExists(socketPath);
|
||||
|
||||
// Create parent directories
|
||||
Files.createDirectories(socketPath.getParent());
|
||||
|
||||
// Create and bind the server socket
|
||||
UnixDomainSocketAddress address = UnixDomainSocketAddress.of(socketPath);
|
||||
serverChannel = ServerSocketChannel.open(StandardProtocolFamily.UNIX);
|
||||
serverChannel.bind(address);
|
||||
|
||||
LOG.info("IPC server started on {}", socketPath);
|
||||
|
||||
// Start accept loop in separate thread
|
||||
executor.submit(this::acceptLoop);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the IPC server.
|
||||
*/
|
||||
public void stop() {
|
||||
if (!running.getAndSet(false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
LOG.info("Stopping IPC server");
|
||||
|
||||
// Close server socket to interrupt accept
|
||||
if (serverChannel != null) {
|
||||
try {
|
||||
serverChannel.close();
|
||||
} catch (IOException e) {
|
||||
LOG.warn("Error closing server socket: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Shutdown executor
|
||||
executor.shutdownNow();
|
||||
|
||||
// Clean up socket file
|
||||
try {
|
||||
Files.deleteIfExists(socketPath);
|
||||
} catch (IOException e) {
|
||||
LOG.warn("Error deleting socket file: {}", e.getMessage());
|
||||
}
|
||||
|
||||
LOG.info("IPC server stopped");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the server is running.
|
||||
*
|
||||
* @return true if running
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
return running.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the socket path.
|
||||
*
|
||||
* @return the socket path
|
||||
*/
|
||||
public Path getSocketPath() {
|
||||
return socketPath;
|
||||
}
|
||||
|
||||
private void acceptLoop() {
|
||||
while (running.get()) {
|
||||
try {
|
||||
SocketChannel clientChannel = serverChannel.accept();
|
||||
LOG.debug("Accepted IPC connection");
|
||||
executor.submit(() -> handleConnection(clientChannel));
|
||||
} catch (IOException e) {
|
||||
if (running.get()) {
|
||||
LOG.error("Error accepting connection: {}", e.getMessage());
|
||||
}
|
||||
// If not running, this is expected during shutdown
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void handleConnection(SocketChannel clientChannel) {
|
||||
try (clientChannel) {
|
||||
BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(Channels.newInputStream(clientChannel), StandardCharsets.UTF_8)
|
||||
);
|
||||
PrintWriter writer = new PrintWriter(
|
||||
new OutputStreamWriter(Channels.newOutputStream(clientChannel), StandardCharsets.UTF_8),
|
||||
true
|
||||
);
|
||||
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
LOG.debug("Received IPC request: {}", line);
|
||||
|
||||
IpcMessage response;
|
||||
try {
|
||||
IpcMessage request = objectMapper.readValue(line, IpcMessage.class);
|
||||
response = handleRequest(request);
|
||||
} catch (Exception e) {
|
||||
LOG.error("Error handling request: {}", e.getMessage(), e);
|
||||
response = IpcMessage.errorResponse(IpcErrorCode.INTERNAL_ERROR, e.getMessage());
|
||||
}
|
||||
|
||||
String responseJson = objectMapper.writeValueAsString(response);
|
||||
LOG.debug("Sending IPC response: {}", responseJson);
|
||||
writer.println(responseJson);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
LOG.debug("Connection closed: {}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private IpcMessage handleRequest(IpcMessage request) {
|
||||
String type = request.getType();
|
||||
if (type == null) {
|
||||
return IpcMessage.errorResponse(IpcErrorCode.INVALID_REQUEST, "Missing request type");
|
||||
}
|
||||
|
||||
try {
|
||||
Object result = handler.handle(type, request.getPayload());
|
||||
return IpcMessage.okResponse(result);
|
||||
} catch (IpcException e) {
|
||||
return IpcMessage.errorResponse(e.getCode(), e.getMessage());
|
||||
} catch (Exception e) {
|
||||
LOG.error("Unexpected error handling request: {}", e.getMessage(), e);
|
||||
return IpcMessage.errorResponse(IpcErrorCode.INTERNAL_ERROR, e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for handling IPC requests.
|
||||
*/
|
||||
@FunctionalInterface
|
||||
public interface RequestHandler {
|
||||
|
||||
/**
|
||||
* Handles an IPC request.
|
||||
*
|
||||
* @param type the request type
|
||||
* @param payload the request payload (may be null)
|
||||
* @return the response payload
|
||||
* @throws IpcException if the request fails
|
||||
*/
|
||||
Object handle(String type, Object payload) throws IpcException;
|
||||
}
|
||||
}
|
||||
@@ -265,13 +265,30 @@ public class JobRepository {
|
||||
* @throws IOException if update fails
|
||||
*/
|
||||
public void scheduleRetry(String id, Instant retryAt) throws IOException {
|
||||
scheduleRetry(id, retryAt, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedules a job for retry with history recording.
|
||||
*
|
||||
* @param id the job ID
|
||||
* @param retryAt when to retry
|
||||
* @param exitCode the exit code from the failed attempt (may be null)
|
||||
* @param error the error message from the failed attempt (may be null)
|
||||
* @throws IOException if update fails
|
||||
*/
|
||||
public void scheduleRetry(String id, Instant retryAt, Integer exitCode, String error) throws IOException {
|
||||
Objects.requireNonNull(id, "id must not be null");
|
||||
Objects.requireNonNull(retryAt, "retryAt must not be null");
|
||||
|
||||
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
|
||||
|
||||
// Increment retry count
|
||||
// Record retry history entry before incrementing count
|
||||
int currentCount = stateFiles.readRetryCount().orElse(0);
|
||||
String historyEntry = formatRetryHistoryEntry(currentCount, exitCode, error);
|
||||
stateFiles.appendRetryHistory(historyEntry);
|
||||
|
||||
// Increment retry count
|
||||
stateFiles.writeRetryCount(currentCount + 1);
|
||||
stateFiles.writeRetryAt(retryAt);
|
||||
|
||||
@@ -281,10 +298,26 @@ public class JobRepository {
|
||||
// Clear runtime state
|
||||
stateFiles.writeStartedAt(null);
|
||||
stateFiles.writeHeartbeat(null);
|
||||
stateFiles.writeFinishedAt(null);
|
||||
|
||||
LOG.info("Job {} scheduled for retry at {} (attempt {})", id, retryAt, currentCount + 1);
|
||||
}
|
||||
|
||||
private String formatRetryHistoryEntry(int attempt, Integer exitCode, String error) {
|
||||
StringBuilder entry = new StringBuilder();
|
||||
entry.append(Instant.now().toString());
|
||||
entry.append("|attempt=").append(attempt + 1);
|
||||
if (exitCode != null) {
|
||||
entry.append("|exit_code=").append(exitCode);
|
||||
}
|
||||
if (error != null) {
|
||||
// Escape newlines and pipes in error message
|
||||
String safeError = error.replace("\n", " ").replace("|", ";");
|
||||
entry.append("|error=").append(safeError);
|
||||
}
|
||||
return entry.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks a job as canceled.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
package com.samsonmedia.barn.jobs;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
|
||||
/**
|
||||
* Calculator for job retry logic with exponential backoff.
|
||||
*
|
||||
* <p>This class determines whether a failed job should be retried and calculates
|
||||
* the delay before the next retry attempt using exponential backoff.
|
||||
*
|
||||
* <p>The delay formula is: {@code delay = base_delay * (multiplier ^ retry_count)}
|
||||
*
|
||||
* <p>With default settings (30s base, 2.0x multiplier):
|
||||
* <ul>
|
||||
* <li>Retry 1: 30 * 2^0 = 30 seconds</li>
|
||||
* <li>Retry 2: 30 * 2^1 = 60 seconds</li>
|
||||
* <li>Retry 3: 30 * 2^2 = 120 seconds</li>
|
||||
* </ul>
|
||||
*
|
||||
* <p>A small amount of jitter (±20%) is added to prevent thundering herd issues.
|
||||
*/
|
||||
public class RetryCalculator {
|
||||
|
||||
private static final double JITTER_MIN = 0.8;
|
||||
private static final double JITTER_MAX = 1.2;
|
||||
private static final long MAX_DELAY_SECONDS = 3600; // 1 hour max delay
|
||||
|
||||
private final JobsConfig config;
|
||||
|
||||
/**
|
||||
* Creates a RetryCalculator with the specified configuration.
|
||||
*
|
||||
* @param config the jobs configuration
|
||||
*/
|
||||
public RetryCalculator(JobsConfig config) {
|
||||
this.config = Objects.requireNonNull(config, "config must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a job should be retried based on its current state and configuration.
|
||||
*
|
||||
* @param job the job to check
|
||||
* @return true if the job should be retried
|
||||
*/
|
||||
public boolean shouldRetry(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
|
||||
// Check if retries are enabled (maxRetries > 0)
|
||||
if (config.maxRetries() == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if we've exhausted all retries
|
||||
if (job.retryCount() >= config.maxRetries()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the exit code is retryable
|
||||
if (job.exitCode() == null) {
|
||||
return false; // No exit code means job didn't complete normally
|
||||
}
|
||||
|
||||
if (!isRetryableExitCode(job.exitCode())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines if a job should be retried using per-job override settings.
|
||||
*
|
||||
* @param job the job to check
|
||||
* @param maxRetries the per-job max retries override
|
||||
* @param retryExitCodes the per-job retry exit codes override (null = use config)
|
||||
* @return true if the job should be retried
|
||||
*/
|
||||
public boolean shouldRetry(Job job, int maxRetries, List<Integer> retryExitCodes) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
|
||||
// Check if retries are enabled
|
||||
if (maxRetries == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if we've exhausted all retries
|
||||
if (job.retryCount() >= maxRetries) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the exit code is retryable
|
||||
if (job.exitCode() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<Integer> exitCodes = retryExitCodes != null ? retryExitCodes : config.retryOnExitCodes();
|
||||
if (!isRetryableExitCode(job.exitCode(), exitCodes)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the delay duration before the next retry attempt.
|
||||
*
|
||||
* <p>Uses exponential backoff with optional jitter.
|
||||
*
|
||||
* @param retryCount the current retry count (0-based)
|
||||
* @return the delay duration
|
||||
*/
|
||||
public Duration calculateDelay(int retryCount) {
|
||||
return calculateDelay(retryCount, config.retryDelaySeconds(), config.retryBackoffMultiplier());
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the delay duration with custom settings.
|
||||
*
|
||||
* @param retryCount the current retry count (0-based)
|
||||
* @param baseDelaySeconds the base delay in seconds
|
||||
* @param multiplier the backoff multiplier
|
||||
* @return the delay duration
|
||||
*/
|
||||
public Duration calculateDelay(int retryCount, int baseDelaySeconds, double multiplier) {
|
||||
if (retryCount < 0) {
|
||||
throw new IllegalArgumentException("retryCount must be non-negative");
|
||||
}
|
||||
if (baseDelaySeconds < 0) {
|
||||
throw new IllegalArgumentException("baseDelaySeconds must be non-negative");
|
||||
}
|
||||
if (multiplier < 1.0) {
|
||||
throw new IllegalArgumentException("multiplier must be at least 1.0");
|
||||
}
|
||||
|
||||
// Calculate base delay: delay = base_delay * (multiplier ^ retry_count)
|
||||
double delaySeconds = baseDelaySeconds * Math.pow(multiplier, retryCount);
|
||||
|
||||
// Apply jitter to prevent thundering herd
|
||||
double jitter = ThreadLocalRandom.current().nextDouble(JITTER_MIN, JITTER_MAX);
|
||||
delaySeconds = delaySeconds * jitter;
|
||||
|
||||
// Cap at maximum delay
|
||||
delaySeconds = Math.min(delaySeconds, MAX_DELAY_SECONDS);
|
||||
|
||||
return Duration.ofSeconds((long) delaySeconds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the delay duration without jitter (for testing).
|
||||
*
|
||||
* @param retryCount the current retry count (0-based)
|
||||
* @return the delay duration without jitter
|
||||
*/
|
||||
Duration calculateDelayWithoutJitter(int retryCount) {
|
||||
return calculateDelayWithoutJitter(retryCount, config.retryDelaySeconds(), config.retryBackoffMultiplier());
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the delay duration without jitter (for testing).
|
||||
*
|
||||
* @param retryCount the current retry count (0-based)
|
||||
* @param baseDelaySeconds the base delay in seconds
|
||||
* @param multiplier the backoff multiplier
|
||||
* @return the delay duration without jitter
|
||||
*/
|
||||
Duration calculateDelayWithoutJitter(int retryCount, int baseDelaySeconds, double multiplier) {
|
||||
if (retryCount < 0) {
|
||||
throw new IllegalArgumentException("retryCount must be non-negative");
|
||||
}
|
||||
|
||||
double delaySeconds = baseDelaySeconds * Math.pow(multiplier, retryCount);
|
||||
delaySeconds = Math.min(delaySeconds, MAX_DELAY_SECONDS);
|
||||
return Duration.ofSeconds((long) delaySeconds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the instant when a job should be retried.
|
||||
*
|
||||
* @param job the job to schedule for retry
|
||||
* @return the retry timestamp
|
||||
*/
|
||||
public Instant calculateRetryAt(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
Duration delay = calculateDelay(job.retryCount());
|
||||
return Instant.now().plus(delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the instant when a job should be retried with custom settings.
|
||||
*
|
||||
* @param job the job to schedule for retry
|
||||
* @param baseDelaySeconds the base delay in seconds
|
||||
* @param multiplier the backoff multiplier
|
||||
* @return the retry timestamp
|
||||
*/
|
||||
public Instant calculateRetryAt(Job job, int baseDelaySeconds, double multiplier) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
Duration delay = calculateDelay(job.retryCount(), baseDelaySeconds, multiplier);
|
||||
return Instant.now().plus(delay);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the maximum number of retries from configuration.
|
||||
*
|
||||
* @return the maximum retries
|
||||
*/
|
||||
public int getMaxRetries() {
|
||||
return config.maxRetries();
|
||||
}
|
||||
|
||||
private boolean isRetryableExitCode(int exitCode) {
|
||||
return isRetryableExitCode(exitCode, config.retryOnExitCodes());
|
||||
}
|
||||
|
||||
private boolean isRetryableExitCode(int exitCode, List<Integer> retryExitCodes) {
|
||||
// Exit code 0 is success, never retry
|
||||
if (exitCode == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// If no exit codes specified, retry all non-zero exit codes
|
||||
if (retryExitCodes == null || retryExitCodes.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if exit code is in the retry list
|
||||
return retryExitCodes.contains(exitCode);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
package com.samsonmedia.barn.logging;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.MDC;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
|
||||
/**
|
||||
* Mapped Diagnostic Context (MDC) wrapper for job-scoped logging.
|
||||
*
|
||||
* <p>Provides automatic context management for job-related log messages.
|
||||
* Use with try-with-resources to ensure proper cleanup:
|
||||
*
|
||||
* <pre>{@code
|
||||
* try (var ctx = JobContext.forJob(job)) {
|
||||
* LOG.info("Processing started"); // Automatically includes jobId
|
||||
* }
|
||||
* }</pre>
|
||||
*/
|
||||
public final class JobContext implements AutoCloseable {
|
||||
|
||||
/** MDC key for job ID. */
|
||||
public static final String KEY_JOB_ID = "jobId";
|
||||
|
||||
/** MDC key for job tag. */
|
||||
public static final String KEY_JOB_TAG = "jobTag";
|
||||
|
||||
private JobContext() {
|
||||
// Private constructor - use factory method
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a job context and sets MDC values.
|
||||
*
|
||||
* @param job the job to create context for
|
||||
* @return a new job context (must be closed)
|
||||
* @throws NullPointerException if job is null
|
||||
*/
|
||||
public static JobContext forJob(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
|
||||
MDC.put(KEY_JOB_ID, job.id());
|
||||
if (job.tag() != null) {
|
||||
MDC.put(KEY_JOB_TAG, job.tag());
|
||||
}
|
||||
|
||||
return new JobContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a job context with just the job ID.
|
||||
*
|
||||
* @param jobId the job ID
|
||||
* @return a new job context (must be closed)
|
||||
* @throws NullPointerException if jobId is null
|
||||
*/
|
||||
public static JobContext forJobId(String jobId) {
|
||||
Objects.requireNonNull(jobId, "jobId must not be null");
|
||||
|
||||
MDC.put(KEY_JOB_ID, jobId);
|
||||
return new JobContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current job ID from MDC.
|
||||
*
|
||||
* @return the job ID, or null if not set
|
||||
*/
|
||||
public static String getCurrentJobId() {
|
||||
return MDC.get(KEY_JOB_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current job tag from MDC.
|
||||
*
|
||||
* @return the job tag, or null if not set
|
||||
*/
|
||||
public static String getCurrentJobTag() {
|
||||
return MDC.get(KEY_JOB_TAG);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
MDC.remove(KEY_JOB_ID);
|
||||
MDC.remove(KEY_JOB_TAG);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package com.samsonmedia.barn.logging;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
|
||||
/**
|
||||
* Structured log events for job lifecycle.
|
||||
*
|
||||
* <p>Provides consistent, structured logging for all job-related events.
|
||||
*/
|
||||
public final class JobLogEvents {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(JobLogEvents.class);
|
||||
|
||||
private JobLogEvents() {
|
||||
// Utility class
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a job creation event.
|
||||
*
|
||||
* @param job the created job
|
||||
* @throws NullPointerException if job is null
|
||||
*/
|
||||
public static void jobCreated(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
LOG.info("Job created: id={} command={} tag={}",
|
||||
job.id(), formatCommand(job), job.tag());
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a job started event.
|
||||
*
|
||||
* @param job the started job
|
||||
* @throws NullPointerException if job is null
|
||||
*/
|
||||
public static void jobStarted(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
LOG.info("Job started: id={} pid={}",
|
||||
job.id(), job.pid());
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a job completion event (success or failure).
|
||||
*
|
||||
* @param job the completed job
|
||||
* @param duration the job duration
|
||||
* @throws NullPointerException if job or duration is null
|
||||
*/
|
||||
public static void jobCompleted(Job job, Duration duration) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
Objects.requireNonNull(duration, "duration must not be null");
|
||||
|
||||
if (job.exitCode() != null && job.exitCode() == 0) {
|
||||
LOG.info("Job succeeded: id={} duration={}ms",
|
||||
job.id(), duration.toMillis());
|
||||
} else {
|
||||
LOG.warn("Job failed: id={} exitCode={} error={}",
|
||||
job.id(), job.exitCode(), job.error());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a job retry scheduled event.
|
||||
*
|
||||
* @param job the job being retried
|
||||
* @param retryAt when the retry will occur
|
||||
* @throws NullPointerException if job or retryAt is null
|
||||
*/
|
||||
public static void jobRetryScheduled(Job job, Instant retryAt) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
Objects.requireNonNull(retryAt, "retryAt must not be null");
|
||||
LOG.info("Job retry scheduled: id={} attempt={} retryAt={}",
|
||||
job.id(), job.retryCount() + 1, retryAt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a job cancellation event.
|
||||
*
|
||||
* @param job the cancelled job
|
||||
* @throws NullPointerException if job is null
|
||||
*/
|
||||
public static void jobCancelled(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
LOG.info("Job cancelled: id={}", job.id());
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a job timeout event.
|
||||
*
|
||||
* @param job the timed-out job
|
||||
* @throws NullPointerException if job is null
|
||||
*/
|
||||
public static void jobTimedOut(Job job) {
|
||||
Objects.requireNonNull(job, "job must not be null");
|
||||
LOG.warn("Job timed out: id={}", job.id());
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a job cleanup event.
|
||||
*
|
||||
* @param jobId the cleaned-up job ID
|
||||
* @throws NullPointerException if jobId is null
|
||||
*/
|
||||
public static void jobCleaned(String jobId) {
|
||||
Objects.requireNonNull(jobId, "jobId must not be null");
|
||||
LOG.debug("Job cleaned: id={}", jobId);
|
||||
}
|
||||
|
||||
private static String formatCommand(Job job) {
|
||||
if (job.command() == null || job.command().isEmpty()) {
|
||||
return "[]";
|
||||
}
|
||||
if (job.command().size() == 1) {
|
||||
return job.command().get(0);
|
||||
}
|
||||
return String.join(" ", job.command());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package com.samsonmedia.barn.logging;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.LogLevel;
|
||||
|
||||
import ch.qos.logback.classic.Level;
|
||||
import ch.qos.logback.classic.Logger;
|
||||
import ch.qos.logback.classic.LoggerContext;
|
||||
|
||||
/**
|
||||
* Configuration utilities for the logging system.
|
||||
*
|
||||
* <p>Provides runtime control over log levels and log directory setup.
|
||||
*/
|
||||
public final class LoggingConfig {
|
||||
|
||||
private LoggingConfig() {
|
||||
// Utility class
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the root log level at runtime.
|
||||
*
|
||||
* @param level the log level to set
|
||||
* @throws NullPointerException if level is null
|
||||
*/
|
||||
public static void setLogLevel(LogLevel level) {
|
||||
Objects.requireNonNull(level, "level must not be null");
|
||||
|
||||
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
|
||||
Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
rootLogger.setLevel(toLogbackLevel(level));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current root log level.
|
||||
*
|
||||
* @return the current log level
|
||||
*/
|
||||
public static LogLevel getLogLevel() {
|
||||
LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
|
||||
Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
|
||||
return fromLogbackLevel(rootLogger.getLevel());
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensures the log directory exists.
|
||||
*
|
||||
* @param logDir the log directory path
|
||||
* @throws IOException if the directory cannot be created
|
||||
*/
|
||||
public static void ensureLogDirectory(Path logDir) throws IOException {
|
||||
Objects.requireNonNull(logDir, "logDir must not be null");
|
||||
if (!Files.exists(logDir)) {
|
||||
Files.createDirectories(logDir);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the default log directory.
|
||||
*
|
||||
* @return the default log directory path
|
||||
*/
|
||||
public static Path getDefaultLogDirectory() {
|
||||
String barnLogDir = System.getProperty("BARN_LOG_DIR");
|
||||
if (barnLogDir != null && !barnLogDir.isEmpty()) {
|
||||
return Path.of(barnLogDir);
|
||||
}
|
||||
String envLogDir = System.getenv("BARN_LOG_DIR");
|
||||
if (envLogDir != null && !envLogDir.isEmpty()) {
|
||||
return Path.of(envLogDir);
|
||||
}
|
||||
return Path.of(System.getProperty("java.io.tmpdir"), "barn", "logs");
|
||||
}
|
||||
|
||||
private static Level toLogbackLevel(LogLevel level) {
|
||||
return switch (level) {
|
||||
case DEBUG -> Level.DEBUG;
|
||||
case INFO -> Level.INFO;
|
||||
case WARN -> Level.WARN;
|
||||
case ERROR -> Level.ERROR;
|
||||
};
|
||||
}
|
||||
|
||||
private static LogLevel fromLogbackLevel(Level level) {
|
||||
if (level == null || level.equals(Level.INFO)) {
|
||||
return LogLevel.INFO;
|
||||
}
|
||||
if (level.equals(Level.DEBUG) || level.equals(Level.TRACE)) {
|
||||
return LogLevel.DEBUG;
|
||||
}
|
||||
if (level.equals(Level.WARN)) {
|
||||
return LogLevel.WARN;
|
||||
}
|
||||
if (level.equals(Level.ERROR) || level.equals(Level.OFF)) {
|
||||
return LogLevel.ERROR;
|
||||
}
|
||||
return LogLevel.INFO;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,276 @@
|
||||
package com.samsonmedia.barn.monitoring;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Collects resource usage metrics for a process.
|
||||
*
|
||||
* <p>Uses OS-specific commands to gather CPU, memory, disk, and GPU usage.
|
||||
*/
|
||||
public class UsageCollector {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(UsageCollector.class);
|
||||
private static final int COMMAND_TIMEOUT_SECONDS = 5;
|
||||
|
||||
private final boolean isWindows;
|
||||
private final boolean isMac;
|
||||
private final boolean isLinux;
|
||||
|
||||
/**
|
||||
* Creates a new UsageCollector.
|
||||
*/
|
||||
public UsageCollector() {
|
||||
String os = System.getProperty("os.name").toLowerCase();
|
||||
this.isWindows = os.contains("win");
|
||||
this.isMac = os.contains("mac");
|
||||
this.isLinux = os.contains("linux");
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects usage metrics for a process.
|
||||
*
|
||||
* @param pid the process ID to monitor
|
||||
* @param workDir the working directory to measure disk usage
|
||||
* @return the collected usage record
|
||||
*/
|
||||
public UsageRecord collect(long pid, Path workDir) {
|
||||
Objects.requireNonNull(workDir, "workDir must not be null");
|
||||
|
||||
Instant timestamp = Instant.now();
|
||||
double cpuPercent = collectCpuUsage(pid);
|
||||
long memoryBytes = collectMemoryUsage(pid);
|
||||
long diskBytes = collectDiskUsage(workDir);
|
||||
Double gpuPercent = collectGpuUsage();
|
||||
Long gpuMemoryBytes = collectGpuMemory();
|
||||
|
||||
return new UsageRecord(timestamp, cpuPercent, memoryBytes, diskBytes, gpuPercent, gpuMemoryBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects CPU usage percentage for a process.
|
||||
*
|
||||
* @param pid the process ID
|
||||
* @return CPU usage as a percentage (0-100+)
|
||||
*/
|
||||
double collectCpuUsage(long pid) {
|
||||
try {
|
||||
if (isWindows) {
|
||||
return collectCpuWindows(pid);
|
||||
} else if (isMac) {
|
||||
return collectCpuMac(pid);
|
||||
} else if (isLinux) {
|
||||
return collectCpuLinux(pid);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debug("Failed to collect CPU usage for PID {}: {}", pid, e.getMessage());
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects memory usage for a process.
|
||||
*
|
||||
* @param pid the process ID
|
||||
* @return memory usage in bytes
|
||||
*/
|
||||
long collectMemoryUsage(long pid) {
|
||||
try {
|
||||
if (isWindows) {
|
||||
return collectMemoryWindows(pid);
|
||||
} else if (isMac) {
|
||||
return collectMemoryMac(pid);
|
||||
} else if (isLinux) {
|
||||
return collectMemoryLinux(pid);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debug("Failed to collect memory usage for PID {}: {}", pid, e.getMessage());
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects disk usage for a directory.
|
||||
*
|
||||
* @param path the directory path
|
||||
* @return disk usage in bytes
|
||||
*/
|
||||
long collectDiskUsage(Path path) {
|
||||
if (!Files.exists(path)) {
|
||||
return 0L;
|
||||
}
|
||||
|
||||
try {
|
||||
return calculateDirectorySize(path);
|
||||
} catch (Exception e) {
|
||||
LOG.debug("Failed to collect disk usage for {}: {}", path, e.getMessage());
|
||||
return 0L;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects GPU usage percentage.
|
||||
*
|
||||
* @return GPU usage as a percentage, or null if not available
|
||||
*/
|
||||
Double collectGpuUsage() {
|
||||
try {
|
||||
Optional<String> result = runCommand("nvidia-smi", "--query-gpu=utilization.gpu",
|
||||
"--format=csv,noheader,nounits");
|
||||
if (result.isPresent()) {
|
||||
return Double.parseDouble(result.get().trim());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.trace("GPU usage not available: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collects GPU memory usage.
|
||||
*
|
||||
* @return GPU memory usage in bytes, or null if not available
|
||||
*/
|
||||
Long collectGpuMemory() {
|
||||
try {
|
||||
Optional<String> result = runCommand("nvidia-smi", "--query-gpu=memory.used",
|
||||
"--format=csv,noheader,nounits");
|
||||
if (result.isPresent()) {
|
||||
// nvidia-smi returns MiB
|
||||
long mib = Long.parseLong(result.get().trim());
|
||||
return mib * 1024 * 1024;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.trace("GPU memory not available: {}", e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private double collectCpuWindows(long pid) throws IOException, InterruptedException {
|
||||
// Use WMIC to get CPU usage
|
||||
Optional<String> result = runCommand("wmic", "path", "Win32_PerfFormattedData_PerfProc_Process",
|
||||
"where", "IDProcess=" + pid, "get", "PercentProcessorTime", "/value");
|
||||
if (result.isPresent()) {
|
||||
String output = result.get();
|
||||
for (String line : output.split("\n")) {
|
||||
if (line.startsWith("PercentProcessorTime=")) {
|
||||
return Double.parseDouble(line.split("=")[1].trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
private double collectCpuMac(long pid) throws IOException, InterruptedException {
|
||||
// Use ps to get CPU percentage
|
||||
Optional<String> result = runCommand("ps", "-p", String.valueOf(pid), "-o", "%cpu=");
|
||||
if (result.isPresent()) {
|
||||
return Double.parseDouble(result.get().trim());
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
private double collectCpuLinux(long pid) throws IOException, InterruptedException {
|
||||
// Use ps to get CPU percentage
|
||||
Optional<String> result = runCommand("ps", "-p", String.valueOf(pid), "-o", "%cpu=");
|
||||
if (result.isPresent()) {
|
||||
return Double.parseDouble(result.get().trim());
|
||||
}
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
private long collectMemoryWindows(long pid) throws IOException, InterruptedException {
|
||||
// Use WMIC to get working set size
|
||||
Optional<String> result = runCommand("wmic", "process", "where", "ProcessId=" + pid,
|
||||
"get", "WorkingSetSize", "/value");
|
||||
if (result.isPresent()) {
|
||||
String output = result.get();
|
||||
for (String line : output.split("\n")) {
|
||||
if (line.startsWith("WorkingSetSize=")) {
|
||||
return Long.parseLong(line.split("=")[1].trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
private long collectMemoryMac(long pid) throws IOException, InterruptedException {
|
||||
// Use ps to get RSS (resident set size) in KB
|
||||
Optional<String> result = runCommand("ps", "-p", String.valueOf(pid), "-o", "rss=");
|
||||
if (result.isPresent()) {
|
||||
long rssKb = Long.parseLong(result.get().trim());
|
||||
return rssKb * 1024; // Convert KB to bytes
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
private long collectMemoryLinux(long pid) throws IOException, InterruptedException {
|
||||
// Use ps to get RSS (resident set size) in KB
|
||||
Optional<String> result = runCommand("ps", "-p", String.valueOf(pid), "-o", "rss=");
|
||||
if (result.isPresent()) {
|
||||
long rssKb = Long.parseLong(result.get().trim());
|
||||
return rssKb * 1024; // Convert KB to bytes
|
||||
}
|
||||
return 0L;
|
||||
}
|
||||
|
||||
private long calculateDirectorySize(Path path) throws IOException {
|
||||
if (!Files.exists(path)) {
|
||||
return 0L;
|
||||
}
|
||||
|
||||
if (Files.isRegularFile(path)) {
|
||||
return Files.size(path);
|
||||
}
|
||||
|
||||
try (Stream<Path> walk = Files.walk(path)) {
|
||||
return walk
|
||||
.filter(Files::isRegularFile)
|
||||
.mapToLong(p -> {
|
||||
try {
|
||||
return Files.size(p);
|
||||
} catch (IOException e) {
|
||||
return 0L;
|
||||
}
|
||||
})
|
||||
.sum();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<String> runCommand(String... command) throws IOException, InterruptedException {
|
||||
ProcessBuilder pb = new ProcessBuilder(command);
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
output.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
boolean finished = process.waitFor(COMMAND_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (!finished) {
|
||||
process.destroyForcibly();
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
if (process.exitValue() != 0) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
return Optional.of(output.toString());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package com.samsonmedia.barn.monitoring;
|
||||
|
||||
import java.io.BufferedWriter;
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Objects;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Writes usage records to a CSV file.
|
||||
*
|
||||
* <p>Thread-safe logger that appends usage records to a file.
|
||||
*/
|
||||
public class UsageLogger implements Closeable {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(UsageLogger.class);
|
||||
|
||||
/** Default filename for usage logs. */
|
||||
public static final String USAGE_LOG_FILENAME = "usage.csv";
|
||||
|
||||
private final Path logFile;
|
||||
private final Object writeLock = new Object();
|
||||
private BufferedWriter writer;
|
||||
private boolean headerWritten;
|
||||
|
||||
/**
|
||||
* Creates a new UsageLogger.
|
||||
*
|
||||
* @param logFile the file to write usage records to
|
||||
*/
|
||||
public UsageLogger(Path logFile) {
|
||||
this.logFile = Objects.requireNonNull(logFile, "logFile must not be null");
|
||||
this.headerWritten = Files.exists(logFile) && fileHasContent(logFile);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a UsageLogger for a job's logs directory.
|
||||
*
|
||||
* @param logsDir the job's logs directory
|
||||
* @return a new UsageLogger
|
||||
*/
|
||||
public static UsageLogger forJobLogsDir(Path logsDir) {
|
||||
return new UsageLogger(logsDir.resolve(USAGE_LOG_FILENAME));
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the log file path.
|
||||
*
|
||||
* @return the log file path
|
||||
*/
|
||||
public Path getLogFile() {
|
||||
return logFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Logs a usage record.
|
||||
*
|
||||
* @param record the usage record to log
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void log(UsageRecord record) throws IOException {
|
||||
Objects.requireNonNull(record, "record must not be null");
|
||||
|
||||
synchronized (writeLock) {
|
||||
ensureWriter();
|
||||
|
||||
if (!headerWritten) {
|
||||
writer.write(UsageRecord.csvHeader());
|
||||
writer.newLine();
|
||||
headerWritten = true;
|
||||
}
|
||||
|
||||
writer.write(record.toCsvLine());
|
||||
writer.newLine();
|
||||
writer.flush();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Flushes any buffered data to the file.
|
||||
*
|
||||
* @throws IOException if flushing fails
|
||||
*/
|
||||
public void flush() throws IOException {
|
||||
synchronized (writeLock) {
|
||||
if (writer != null) {
|
||||
writer.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
synchronized (writeLock) {
|
||||
if (writer != null) {
|
||||
try {
|
||||
writer.close();
|
||||
} finally {
|
||||
writer = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ensureWriter() throws IOException {
|
||||
if (writer == null) {
|
||||
Path parent = logFile.getParent();
|
||||
if (parent != null && !Files.exists(parent)) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
|
||||
writer = Files.newBufferedWriter(logFile,
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.APPEND);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean fileHasContent(Path file) {
|
||||
try {
|
||||
return Files.size(file) > 0;
|
||||
} catch (IOException e) {
|
||||
LOG.trace("Could not check file size: {}", e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
package com.samsonmedia.barn.monitoring;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ScheduledFuture;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Monitors resource usage for a process over time.
|
||||
*
|
||||
* <p>Collects usage metrics at regular intervals and logs them to a CSV file.
|
||||
*/
|
||||
public class UsageMonitor implements Closeable {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(UsageMonitor.class);
|
||||
|
||||
/** Default collection interval in seconds. */
|
||||
public static final int DEFAULT_INTERVAL_SECONDS = 5;
|
||||
|
||||
private final UsageCollector collector;
|
||||
private final UsageLogger logger;
|
||||
private final long pid;
|
||||
private final Path workDir;
|
||||
private final int intervalSeconds;
|
||||
private final ScheduledExecutorService scheduler;
|
||||
private final AtomicBoolean running;
|
||||
private ScheduledFuture<?> scheduledTask;
|
||||
|
||||
/**
|
||||
* Creates a new UsageMonitor.
|
||||
*
|
||||
* @param pid the process ID to monitor
|
||||
* @param workDir the working directory to measure disk usage
|
||||
* @param logsDir the directory to write usage logs
|
||||
*/
|
||||
public UsageMonitor(long pid, Path workDir, Path logsDir) {
|
||||
this(pid, workDir, logsDir, DEFAULT_INTERVAL_SECONDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new UsageMonitor with custom interval.
|
||||
*
|
||||
* @param pid the process ID to monitor
|
||||
* @param workDir the working directory to measure disk usage
|
||||
* @param logsDir the directory to write usage logs
|
||||
* @param intervalSeconds collection interval in seconds
|
||||
*/
|
||||
public UsageMonitor(long pid, Path workDir, Path logsDir, int intervalSeconds) {
|
||||
this(new UsageCollector(), UsageLogger.forJobLogsDir(logsDir), pid, workDir, intervalSeconds);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new UsageMonitor with custom components.
|
||||
*
|
||||
* @param collector the usage collector
|
||||
* @param logger the usage logger
|
||||
* @param pid the process ID to monitor
|
||||
* @param workDir the working directory to measure disk usage
|
||||
* @param intervalSeconds collection interval in seconds
|
||||
*/
|
||||
public UsageMonitor(UsageCollector collector, UsageLogger logger, long pid,
|
||||
Path workDir, int intervalSeconds) {
|
||||
this.collector = Objects.requireNonNull(collector, "collector must not be null");
|
||||
this.logger = Objects.requireNonNull(logger, "logger must not be null");
|
||||
this.workDir = Objects.requireNonNull(workDir, "workDir must not be null");
|
||||
|
||||
if (pid <= 0) {
|
||||
throw new IllegalArgumentException("pid must be positive");
|
||||
}
|
||||
if (intervalSeconds <= 0) {
|
||||
throw new IllegalArgumentException("intervalSeconds must be positive");
|
||||
}
|
||||
|
||||
this.pid = pid;
|
||||
this.intervalSeconds = intervalSeconds;
|
||||
this.scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "usage-monitor-" + pid);
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
this.running = new AtomicBoolean(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the usage monitor.
|
||||
*/
|
||||
public void start() {
|
||||
if (running.compareAndSet(false, true)) {
|
||||
LOG.debug("Starting usage monitor for PID {} with interval {}s", pid, intervalSeconds);
|
||||
|
||||
// Collect immediately, then at intervals
|
||||
collectAndLog();
|
||||
|
||||
scheduledTask = scheduler.scheduleAtFixedRate(
|
||||
this::collectAndLog,
|
||||
intervalSeconds,
|
||||
intervalSeconds,
|
||||
TimeUnit.SECONDS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the usage monitor.
|
||||
*/
|
||||
public void stop() {
|
||||
if (running.compareAndSet(true, false)) {
|
||||
LOG.debug("Stopping usage monitor for PID {}", pid);
|
||||
|
||||
if (scheduledTask != null) {
|
||||
scheduledTask.cancel(false);
|
||||
}
|
||||
|
||||
// Collect one final sample
|
||||
collectAndLog();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the monitor is running.
|
||||
*
|
||||
* @return true if running
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
return running.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the log file path.
|
||||
*
|
||||
* @return the log file path
|
||||
*/
|
||||
public Path getLogFile() {
|
||||
return logger.getLogFile();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
stop();
|
||||
scheduler.shutdown();
|
||||
try {
|
||||
if (!scheduler.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
scheduler.shutdownNow();
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
scheduler.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
logger.close();
|
||||
}
|
||||
|
||||
private void collectAndLog() {
|
||||
try {
|
||||
UsageRecord record = collector.collect(pid, workDir);
|
||||
logger.log(record);
|
||||
LOG.trace("Logged usage: CPU={}%, Memory={}, Disk={}",
|
||||
String.format("%.1f", record.cpuPercent()),
|
||||
UsageRecord.formatBytes(record.memoryBytes()),
|
||||
UsageRecord.formatBytes(record.diskBytes()));
|
||||
} catch (Exception e) {
|
||||
LOG.warn("Failed to collect/log usage for PID {}: {}", pid, e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.samsonmedia.barn.monitoring;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Represents a single usage measurement for a process.
|
||||
*
|
||||
* @param timestamp when the measurement was taken
|
||||
* @param cpuPercent CPU usage as a percentage (0-100+)
|
||||
* @param memoryBytes memory usage in bytes
|
||||
* @param diskBytes disk usage in bytes (typically of work directory)
|
||||
* @param gpuPercent GPU usage as a percentage (null if not available)
|
||||
* @param gpuMemoryBytes GPU memory usage in bytes (null if not available)
|
||||
*/
|
||||
public record UsageRecord(
|
||||
Instant timestamp,
|
||||
double cpuPercent,
|
||||
long memoryBytes,
|
||||
long diskBytes,
|
||||
Double gpuPercent,
|
||||
Long gpuMemoryBytes
|
||||
) {
|
||||
|
||||
/**
|
||||
* Creates a UsageRecord with validation.
|
||||
*/
|
||||
public UsageRecord {
|
||||
Objects.requireNonNull(timestamp, "timestamp must not be null");
|
||||
if (cpuPercent < 0) {
|
||||
throw new IllegalArgumentException("cpuPercent must be non-negative");
|
||||
}
|
||||
if (memoryBytes < 0) {
|
||||
throw new IllegalArgumentException("memoryBytes must be non-negative");
|
||||
}
|
||||
if (diskBytes < 0) {
|
||||
throw new IllegalArgumentException("diskBytes must be non-negative");
|
||||
}
|
||||
if (gpuPercent != null && gpuPercent < 0) {
|
||||
throw new IllegalArgumentException("gpuPercent must be non-negative");
|
||||
}
|
||||
if (gpuMemoryBytes != null && gpuMemoryBytes < 0) {
|
||||
throw new IllegalArgumentException("gpuMemoryBytes must be non-negative");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a UsageRecord without GPU information.
|
||||
*
|
||||
* @param timestamp when the measurement was taken
|
||||
* @param cpuPercent CPU usage as a percentage
|
||||
* @param memoryBytes memory usage in bytes
|
||||
* @param diskBytes disk usage in bytes
|
||||
* @return a new UsageRecord
|
||||
*/
|
||||
public static UsageRecord withoutGpu(Instant timestamp, double cpuPercent,
|
||||
long memoryBytes, long diskBytes) {
|
||||
return new UsageRecord(timestamp, cpuPercent, memoryBytes, diskBytes, null, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts this record to a CSV line.
|
||||
*
|
||||
* @return CSV formatted string
|
||||
*/
|
||||
public String toCsvLine() {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(timestamp.toString());
|
||||
sb.append(',').append(String.format("%.2f", cpuPercent));
|
||||
sb.append(',').append(memoryBytes);
|
||||
sb.append(',').append(diskBytes);
|
||||
sb.append(',').append(gpuPercent != null ? String.format("%.2f", gpuPercent) : "");
|
||||
sb.append(',').append(gpuMemoryBytes != null ? gpuMemoryBytes : "");
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the CSV header line.
|
||||
*
|
||||
* @return CSV header
|
||||
*/
|
||||
public static String csvHeader() {
|
||||
return "timestamp,cpu_percent,memory_bytes,disk_bytes,gpu_percent,gpu_memory_bytes";
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a UsageRecord from a CSV line.
|
||||
*
|
||||
* @param line the CSV line
|
||||
* @return the parsed UsageRecord
|
||||
* @throws IllegalArgumentException if the line is invalid
|
||||
*/
|
||||
public static UsageRecord fromCsvLine(String line) {
|
||||
Objects.requireNonNull(line, "line must not be null");
|
||||
String[] parts = line.split(",", -1);
|
||||
if (parts.length < 4) {
|
||||
throw new IllegalArgumentException("Invalid CSV line: " + line);
|
||||
}
|
||||
|
||||
Instant timestamp = Instant.parse(parts[0]);
|
||||
double cpuPercent = Double.parseDouble(parts[1]);
|
||||
long memoryBytes = Long.parseLong(parts[2]);
|
||||
long diskBytes = Long.parseLong(parts[3]);
|
||||
|
||||
Double gpuPercent = null;
|
||||
Long gpuMemoryBytes = null;
|
||||
|
||||
if (parts.length > 4 && !parts[4].isEmpty()) {
|
||||
gpuPercent = Double.parseDouble(parts[4]);
|
||||
}
|
||||
if (parts.length > 5 && !parts[5].isEmpty()) {
|
||||
gpuMemoryBytes = Long.parseLong(parts[5]);
|
||||
}
|
||||
|
||||
return new UsageRecord(timestamp, cpuPercent, memoryBytes, diskBytes, gpuPercent, gpuMemoryBytes);
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats memory size for human display.
|
||||
*
|
||||
* @param bytes the size in bytes
|
||||
* @return human-readable size string
|
||||
*/
|
||||
public static String formatBytes(long bytes) {
|
||||
if (bytes < 1024) {
|
||||
return bytes + " B";
|
||||
}
|
||||
double kb = bytes / 1024.0;
|
||||
if (kb < 1024) {
|
||||
return String.format("%.1f KB", kb);
|
||||
}
|
||||
double mb = kb / 1024.0;
|
||||
if (mb < 1024) {
|
||||
return String.format("%.1f MB", mb);
|
||||
}
|
||||
double gb = mb / 1024.0;
|
||||
return String.format("%.2f GB", gb);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
package com.samsonmedia.barn.platform.linux;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Manages Linux systemd service operations.
|
||||
*
|
||||
* <p>Provides methods for installing, enabling, starting, and stopping
|
||||
* systemd services using the systemctl command.
|
||||
*/
|
||||
public class SystemdManager {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(SystemdManager.class);
|
||||
private static final String SERVICE_NAME = "barn.service";
|
||||
private static final long COMMAND_TIMEOUT_SECONDS = 30;
|
||||
|
||||
/**
|
||||
* Gets the path for the system service unit file.
|
||||
*
|
||||
* @return the system service path
|
||||
*/
|
||||
public Path getSystemServicePath() {
|
||||
return Path.of("/etc/systemd/system", SERVICE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the path for the user service unit file.
|
||||
*
|
||||
* @return the user service path
|
||||
*/
|
||||
public Path getUserServicePath() {
|
||||
String userHome = System.getProperty("user.home");
|
||||
return Path.of(userHome, ".config", "systemd", "user", SERVICE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if systemd is available on this system.
|
||||
*
|
||||
* @return true if systemd is available
|
||||
*/
|
||||
public static boolean hasSystemd() {
|
||||
return Files.exists(Path.of("/run/systemd/system"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current process is running under systemd.
|
||||
*
|
||||
* @return true if running under systemd
|
||||
*/
|
||||
public static boolean isUnderSystemd() {
|
||||
return System.getenv("INVOCATION_ID") != null
|
||||
|| Files.exists(Path.of("/run/systemd/system"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the systemd unit file content.
|
||||
*
|
||||
* @param barnBinaryPath the path to the barn binary
|
||||
* @param barnDir the barn data directory
|
||||
* @param userMode whether this is a user service
|
||||
* @return the unit file content
|
||||
*/
|
||||
public String generateUnitFile(Path barnBinaryPath, Path barnDir, boolean userMode) {
|
||||
Objects.requireNonNull(barnBinaryPath, "barnBinaryPath must not be null");
|
||||
Objects.requireNonNull(barnDir, "barnDir must not be null");
|
||||
|
||||
if (userMode) {
|
||||
return generateUserUnitFile(barnBinaryPath, barnDir);
|
||||
} else {
|
||||
return generateSystemUnitFile(barnBinaryPath, barnDir);
|
||||
}
|
||||
}
|
||||
|
||||
private String generateSystemUnitFile(Path barnBinaryPath, Path barnDir) {
|
||||
return """
|
||||
[Unit]
|
||||
Description=Barn Job Daemon
|
||||
Documentation=https://github.com/samson-media/barn
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=%s service start --foreground --barn-dir %s
|
||||
ExecStop=%s service stop --barn-dir %s
|
||||
ExecReload=/bin/kill -HUP $MAINPID
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
|
||||
# Security hardening
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=read-only
|
||||
PrivateTmp=false
|
||||
ReadWritePaths=%s
|
||||
|
||||
# Logging
|
||||
StandardOutput=journal
|
||||
StandardError=journal
|
||||
SyslogIdentifier=barn
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
""".formatted(
|
||||
barnBinaryPath.toString(),
|
||||
barnDir.toString(),
|
||||
barnBinaryPath.toString(),
|
||||
barnDir.toString(),
|
||||
barnDir.toString()
|
||||
);
|
||||
}
|
||||
|
||||
private String generateUserUnitFile(Path barnBinaryPath, Path barnDir) {
|
||||
return """
|
||||
[Unit]
|
||||
Description=Barn Job Daemon (User)
|
||||
Documentation=https://github.com/samson-media/barn
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=%s service start --foreground --barn-dir %s
|
||||
ExecStop=%s service stop --barn-dir %s
|
||||
Restart=on-failure
|
||||
RestartSec=5
|
||||
|
||||
[Install]
|
||||
WantedBy=default.target
|
||||
""".formatted(
|
||||
barnBinaryPath.toString(),
|
||||
barnDir.toString(),
|
||||
barnBinaryPath.toString(),
|
||||
barnDir.toString()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a unit file to the specified path.
|
||||
*
|
||||
* @param unitPath the destination path
|
||||
* @param content the unit file content
|
||||
* @throws IOException if the file cannot be written
|
||||
*/
|
||||
public void writeUnitFile(Path unitPath, String content) throws IOException {
|
||||
Objects.requireNonNull(unitPath, "unitPath must not be null");
|
||||
Objects.requireNonNull(content, "content must not be null");
|
||||
|
||||
Path parent = unitPath.getParent();
|
||||
if (parent != null && !Files.exists(parent)) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
|
||||
Files.writeString(unitPath, content);
|
||||
LOG.info("Wrote unit file: {}", unitPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a unit file.
|
||||
*
|
||||
* @param unitPath the path to the unit file
|
||||
* @return true if the file was deleted or didn't exist
|
||||
*/
|
||||
public boolean deleteUnitFile(Path unitPath) {
|
||||
Objects.requireNonNull(unitPath, "unitPath must not be null");
|
||||
|
||||
try {
|
||||
boolean deleted = Files.deleteIfExists(unitPath);
|
||||
if (deleted) {
|
||||
LOG.info("Deleted unit file: {}", unitPath);
|
||||
}
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
LOG.error("Failed to delete unit file: {}", unitPath, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the systemd daemon configuration.
|
||||
*
|
||||
* @param userMode whether to reload user services
|
||||
* @throws SystemdException if the reload fails
|
||||
*/
|
||||
public void daemonReload(boolean userMode) {
|
||||
LOG.info("Reloading systemd daemon (userMode={})", userMode);
|
||||
systemctl(userMode, "daemon-reload");
|
||||
}
|
||||
|
||||
/**
|
||||
* Enables the barn service.
|
||||
*
|
||||
* @param userMode whether this is a user service
|
||||
* @throws SystemdException if the enable fails
|
||||
*/
|
||||
public void enable(boolean userMode) {
|
||||
LOG.info("Enabling barn service (userMode={})", userMode);
|
||||
systemctl(userMode, "enable", "barn");
|
||||
}
|
||||
|
||||
/**
|
||||
* Disables the barn service.
|
||||
*
|
||||
* @param userMode whether this is a user service
|
||||
* @throws SystemdException if the disable fails
|
||||
*/
|
||||
public void disable(boolean userMode) {
|
||||
LOG.info("Disabling barn service (userMode={})", userMode);
|
||||
systemctl(userMode, "disable", "barn");
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the barn service.
|
||||
*
|
||||
* @param userMode whether this is a user service
|
||||
* @throws SystemdException if the start fails
|
||||
*/
|
||||
public void start(boolean userMode) {
|
||||
LOG.info("Starting barn service (userMode={})", userMode);
|
||||
systemctl(userMode, "start", "barn");
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the barn service.
|
||||
*
|
||||
* @param userMode whether this is a user service
|
||||
* @throws SystemdException if the stop fails
|
||||
*/
|
||||
public void stop(boolean userMode) {
|
||||
LOG.info("Stopping barn service (userMode={})", userMode);
|
||||
systemctl(userMode, "stop", "barn");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the barn service is enabled.
|
||||
*
|
||||
* @param userMode whether this is a user service
|
||||
* @return true if the service is enabled
|
||||
*/
|
||||
public boolean isEnabled(boolean userMode) {
|
||||
try {
|
||||
int exitCode = systemctlWithExitCode(userMode, "is-enabled", "barn");
|
||||
return exitCode == 0;
|
||||
} catch (SystemdException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the barn service is active (running).
|
||||
*
|
||||
* @param userMode whether this is a user service
|
||||
* @return true if the service is active
|
||||
*/
|
||||
public boolean isActive(boolean userMode) {
|
||||
try {
|
||||
int exitCode = systemctlWithExitCode(userMode, "is-active", "barn");
|
||||
return exitCode == 0;
|
||||
} catch (SystemdException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the journal logs for the barn service.
|
||||
*
|
||||
* @param userMode whether this is a user service
|
||||
* @param lines number of lines to retrieve
|
||||
* @return the log output
|
||||
* @throws SystemdException if the command fails
|
||||
*/
|
||||
public String getLogs(boolean userMode, int lines) {
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add("journalctl");
|
||||
if (userMode) {
|
||||
command.add("--user");
|
||||
}
|
||||
command.add("-u");
|
||||
command.add("barn");
|
||||
command.add("-n");
|
||||
command.add(String.valueOf(lines));
|
||||
command.add("--no-pager");
|
||||
|
||||
return execWithOutput(command);
|
||||
}
|
||||
|
||||
private void systemctl(boolean userMode, String... args) {
|
||||
List<String> command = buildSystemctlCommand(userMode, args);
|
||||
int exitCode = exec(command);
|
||||
if (exitCode != 0) {
|
||||
throw new SystemdException("systemctl command failed: " + String.join(" ", command));
|
||||
}
|
||||
}
|
||||
|
||||
private int systemctlWithExitCode(boolean userMode, String... args) {
|
||||
List<String> command = buildSystemctlCommand(userMode, args);
|
||||
return exec(command);
|
||||
}
|
||||
|
||||
private List<String> buildSystemctlCommand(boolean userMode, String... args) {
|
||||
List<String> command = new ArrayList<>();
|
||||
command.add("systemctl");
|
||||
if (userMode) {
|
||||
command.add("--user");
|
||||
}
|
||||
for (String arg : args) {
|
||||
command.add(arg);
|
||||
}
|
||||
return command;
|
||||
}
|
||||
|
||||
private int exec(List<String> command) {
|
||||
try {
|
||||
ProcessBuilder pb = new ProcessBuilder(command);
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
|
||||
// Read output to prevent blocking
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
LOG.debug("systemctl: {}", line);
|
||||
}
|
||||
}
|
||||
|
||||
boolean completed = process.waitFor(COMMAND_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (!completed) {
|
||||
process.destroyForcibly();
|
||||
throw new SystemdException("Command timed out: " + String.join(" ", command));
|
||||
}
|
||||
|
||||
return process.exitValue();
|
||||
} catch (IOException | InterruptedException e) {
|
||||
LOG.error("Failed to execute command: {}", String.join(" ", command), e);
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
throw new SystemdException("Failed to execute command: " + String.join(" ", command), e);
|
||||
}
|
||||
}
|
||||
|
||||
private String execWithOutput(List<String> command) {
|
||||
try {
|
||||
ProcessBuilder pb = new ProcessBuilder(command);
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
output.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
boolean completed = process.waitFor(COMMAND_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (!completed) {
|
||||
process.destroyForcibly();
|
||||
throw new SystemdException("Command timed out: " + String.join(" ", command));
|
||||
}
|
||||
|
||||
return output.toString();
|
||||
} catch (IOException | InterruptedException e) {
|
||||
LOG.error("Failed to execute command: {}", String.join(" ", command), e);
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
throw new SystemdException("Failed to execute command: " + String.join(" ", command), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception thrown when a systemd operation fails.
|
||||
*/
|
||||
public static class SystemdException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Creates a new SystemdException.
|
||||
*
|
||||
* @param message the error message
|
||||
*/
|
||||
public SystemdException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new SystemdException with a cause.
|
||||
*
|
||||
* @param message the error message
|
||||
* @param cause the underlying cause
|
||||
*/
|
||||
public SystemdException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
package com.samsonmedia.barn.platform.macos;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Manages macOS launchd service operations.
|
||||
*
|
||||
* <p>Provides methods for loading, unloading, starting, and stopping
|
||||
* launchd services using the launchctl command.
|
||||
*/
|
||||
public class LaunchdManager {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(LaunchdManager.class);
|
||||
private static final String LABEL = "com.samsonmedia.barn";
|
||||
private static final long COMMAND_TIMEOUT_SECONDS = 30;
|
||||
|
||||
/**
|
||||
* Gets the launchd service label.
|
||||
*
|
||||
* @return the service label
|
||||
*/
|
||||
public String getLabel() {
|
||||
return LABEL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the path for the system daemon plist file.
|
||||
*
|
||||
* @return the system daemon plist path
|
||||
*/
|
||||
public Path getSystemDaemonPath() {
|
||||
return Path.of("/Library/LaunchDaemons", LABEL + ".plist");
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the path for the user agent plist file.
|
||||
*
|
||||
* @return the user agent plist path
|
||||
*/
|
||||
public Path getUserAgentPath() {
|
||||
String userHome = System.getProperty("user.home");
|
||||
return Path.of(userHome, "Library", "LaunchAgents", LABEL + ".plist");
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a launchd plist file.
|
||||
*
|
||||
* @param plistPath the path to the plist file
|
||||
* @throws LaunchdException if the load fails
|
||||
*/
|
||||
public void load(Path plistPath) {
|
||||
Objects.requireNonNull(plistPath, "plistPath must not be null");
|
||||
LOG.info("Loading launchd plist: {}", plistPath);
|
||||
|
||||
int exitCode = exec("launchctl", "load", plistPath.toString());
|
||||
if (exitCode != 0) {
|
||||
throw new LaunchdException("Failed to load plist: " + plistPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unloads a launchd plist file.
|
||||
*
|
||||
* @param plistPath the path to the plist file
|
||||
* @throws LaunchdException if the unload fails
|
||||
*/
|
||||
public void unload(Path plistPath) {
|
||||
Objects.requireNonNull(plistPath, "plistPath must not be null");
|
||||
LOG.info("Unloading launchd plist: {}", plistPath);
|
||||
|
||||
int exitCode = exec("launchctl", "unload", plistPath.toString());
|
||||
if (exitCode != 0) {
|
||||
throw new LaunchdException("Failed to unload plist: " + plistPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the service is loaded in launchd.
|
||||
*
|
||||
* @return true if the service is loaded
|
||||
*/
|
||||
public boolean isLoaded() {
|
||||
try {
|
||||
ProcessBuilder pb = new ProcessBuilder("launchctl", "list");
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
if (line.contains(LABEL)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
process.waitFor(COMMAND_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
return false;
|
||||
} catch (IOException | InterruptedException e) {
|
||||
LOG.warn("Failed to check if service is loaded: {}", e.getMessage());
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the launchd service.
|
||||
*
|
||||
* @throws LaunchdException if the start fails
|
||||
*/
|
||||
public void start() {
|
||||
LOG.info("Starting launchd service: {}", LABEL);
|
||||
int exitCode = exec("launchctl", "start", LABEL);
|
||||
if (exitCode != 0) {
|
||||
throw new LaunchdException("Failed to start service: " + LABEL);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the launchd service.
|
||||
*
|
||||
* @throws LaunchdException if the stop fails
|
||||
*/
|
||||
public void stop() {
|
||||
LOG.info("Stopping launchd service: {}", LABEL);
|
||||
int exitCode = exec("launchctl", "stop", LABEL);
|
||||
if (exitCode != 0) {
|
||||
throw new LaunchdException("Failed to stop service: " + LABEL);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current process is running under launchd.
|
||||
*
|
||||
* @return true if running under launchd
|
||||
*/
|
||||
public static boolean isUnderLaunchd() {
|
||||
// Check for launchd environment variable
|
||||
if (System.getenv("__CFBundleIdentifier") != null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Check if parent process is launchd
|
||||
return ProcessHandle.current().parent()
|
||||
.map(p -> p.info().command().orElse(""))
|
||||
.map(c -> c.contains("launchd"))
|
||||
.orElse(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates the plist content for the launchd service.
|
||||
*
|
||||
* @param barnBinaryPath the path to the barn binary
|
||||
* @param barnDir the barn data directory
|
||||
* @return the plist XML content
|
||||
*/
|
||||
public String generatePlist(Path barnBinaryPath, Path barnDir) {
|
||||
Objects.requireNonNull(barnBinaryPath, "barnBinaryPath must not be null");
|
||||
Objects.requireNonNull(barnDir, "barnDir must not be null");
|
||||
|
||||
Path logsDir = barnDir.resolve("logs");
|
||||
|
||||
return """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
|
||||
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Label</key>
|
||||
<string>%s</string>
|
||||
|
||||
<key>ProgramArguments</key>
|
||||
<array>
|
||||
<string>%s</string>
|
||||
<string>service</string>
|
||||
<string>start</string>
|
||||
<string>--foreground</string>
|
||||
<string>--barn-dir</string>
|
||||
<string>%s</string>
|
||||
</array>
|
||||
|
||||
<key>RunAtLoad</key>
|
||||
<true/>
|
||||
|
||||
<key>KeepAlive</key>
|
||||
<true/>
|
||||
|
||||
<key>StandardOutPath</key>
|
||||
<string>%s/barn.log</string>
|
||||
|
||||
<key>StandardErrorPath</key>
|
||||
<string>%s/barn.log</string>
|
||||
|
||||
<key>WorkingDirectory</key>
|
||||
<string>%s</string>
|
||||
</dict>
|
||||
</plist>
|
||||
""".formatted(
|
||||
LABEL,
|
||||
barnBinaryPath.toString(),
|
||||
barnDir.toString(),
|
||||
logsDir.toString(),
|
||||
logsDir.toString(),
|
||||
barnDir.toString()
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a plist file to the specified path.
|
||||
*
|
||||
* @param plistPath the destination path
|
||||
* @param content the plist content
|
||||
* @throws IOException if the file cannot be written
|
||||
*/
|
||||
public void writePlist(Path plistPath, String content) throws IOException {
|
||||
Objects.requireNonNull(plistPath, "plistPath must not be null");
|
||||
Objects.requireNonNull(content, "content must not be null");
|
||||
|
||||
Path parent = plistPath.getParent();
|
||||
if (parent != null && !Files.exists(parent)) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
|
||||
Files.writeString(plistPath, content);
|
||||
LOG.info("Wrote plist file: {}", plistPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a plist file.
|
||||
*
|
||||
* @param plistPath the path to the plist file
|
||||
* @return true if the file was deleted or didn't exist
|
||||
*/
|
||||
public boolean deletePlist(Path plistPath) {
|
||||
Objects.requireNonNull(plistPath, "plistPath must not be null");
|
||||
|
||||
try {
|
||||
boolean deleted = Files.deleteIfExists(plistPath);
|
||||
if (deleted) {
|
||||
LOG.info("Deleted plist file: {}", plistPath);
|
||||
}
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
LOG.error("Failed to delete plist file: {}", plistPath, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int exec(String... command) {
|
||||
try {
|
||||
ProcessBuilder pb = new ProcessBuilder(command);
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
|
||||
// Read output to prevent blocking
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
LOG.debug("launchctl: {}", line);
|
||||
}
|
||||
}
|
||||
|
||||
boolean completed = process.waitFor(COMMAND_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (!completed) {
|
||||
process.destroyForcibly();
|
||||
throw new LaunchdException("Command timed out: " + String.join(" ", command));
|
||||
}
|
||||
|
||||
return process.exitValue();
|
||||
} catch (IOException | InterruptedException e) {
|
||||
LOG.error("Failed to execute command: {}", String.join(" ", command), e);
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
throw new LaunchdException("Failed to execute command: " + String.join(" ", command), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception thrown when a launchd operation fails.
|
||||
*/
|
||||
public static class LaunchdException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Creates a new LaunchdException.
|
||||
*
|
||||
* @param message the error message
|
||||
*/
|
||||
public LaunchdException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new LaunchdException with a cause.
|
||||
*
|
||||
* @param message the error message
|
||||
* @param cause the underlying cause
|
||||
*/
|
||||
public LaunchdException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package com.samsonmedia.barn.platform.windows;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* Manages Windows service operations using sc.exe.
|
||||
*
|
||||
* <p>Provides methods for installing, starting, and stopping Windows services
|
||||
* using the built-in sc.exe command.
|
||||
*/
|
||||
public class WindowsServiceManager {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(WindowsServiceManager.class);
|
||||
private static final String SERVICE_NAME = "barn";
|
||||
private static final String DISPLAY_NAME = "Barn Job Daemon";
|
||||
private static final long COMMAND_TIMEOUT_SECONDS = 30;
|
||||
|
||||
/**
|
||||
* Gets the service name.
|
||||
*
|
||||
* @return the service name
|
||||
*/
|
||||
public String getServiceName() {
|
||||
return SERVICE_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the display name for the service.
|
||||
*
|
||||
* @return the display name
|
||||
*/
|
||||
public String getDisplayName() {
|
||||
return DISPLAY_NAME;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the current process is running with administrator privileges.
|
||||
*
|
||||
* @return true if running as administrator
|
||||
*/
|
||||
public static boolean isAdmin() {
|
||||
try {
|
||||
ProcessBuilder pb = new ProcessBuilder("net", "session");
|
||||
pb.redirectError(ProcessBuilder.Redirect.DISCARD);
|
||||
pb.redirectOutput(ProcessBuilder.Redirect.DISCARD);
|
||||
Process process = pb.start();
|
||||
boolean completed = process.waitFor(5, TimeUnit.SECONDS);
|
||||
return completed && process.exitValue() == 0;
|
||||
} catch (IOException | InterruptedException e) {
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if this system supports Windows services.
|
||||
*
|
||||
* @return true if Windows services are supported
|
||||
*/
|
||||
public static boolean hasWindowsServices() {
|
||||
String osName = System.getProperty("os.name", "").toLowerCase();
|
||||
return osName.contains("windows");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the service is running under the Windows Service Control Manager.
|
||||
*
|
||||
* @return true if running as a Windows service
|
||||
*/
|
||||
public static boolean isUnderServiceManager() {
|
||||
// Check for environment variable set by Windows SCM
|
||||
return System.getenv("SERVICE_NAME") != null
|
||||
|| System.getProperty("winsw.id") != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Installs the barn service.
|
||||
*
|
||||
* @param binaryPath the path to the barn binary
|
||||
* @param barnDir the barn data directory
|
||||
* @throws WindowsServiceException if installation fails
|
||||
*/
|
||||
public void install(String binaryPath, String barnDir) {
|
||||
Objects.requireNonNull(binaryPath, "binaryPath must not be null");
|
||||
Objects.requireNonNull(barnDir, "barnDir must not be null");
|
||||
|
||||
LOG.info("Installing Windows service: {}", SERVICE_NAME);
|
||||
|
||||
String binPath = String.format("\"%s\" service start --foreground --barn-dir \"%s\"",
|
||||
binaryPath, barnDir);
|
||||
|
||||
// Create the service
|
||||
exec("sc", "create", SERVICE_NAME,
|
||||
"binPath=" + binPath,
|
||||
"DisplayName=" + DISPLAY_NAME,
|
||||
"start=auto");
|
||||
|
||||
// Set description
|
||||
exec("sc", "description", SERVICE_NAME,
|
||||
"Cross-platform job daemon for media processing");
|
||||
|
||||
// Configure failure recovery (restart after 5 seconds)
|
||||
exec("sc", "failure", SERVICE_NAME,
|
||||
"reset=86400",
|
||||
"actions=restart/5000/restart/5000/restart/5000");
|
||||
|
||||
LOG.info("Windows service installed successfully: {}", SERVICE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Uninstalls the barn service.
|
||||
*
|
||||
* @throws WindowsServiceException if uninstallation fails
|
||||
*/
|
||||
public void uninstall() {
|
||||
LOG.info("Uninstalling Windows service: {}", SERVICE_NAME);
|
||||
exec("sc", "delete", SERVICE_NAME);
|
||||
LOG.info("Windows service uninstalled successfully: {}", SERVICE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the barn service.
|
||||
*
|
||||
* @throws WindowsServiceException if the service fails to start
|
||||
*/
|
||||
public void start() {
|
||||
LOG.info("Starting Windows service: {}", SERVICE_NAME);
|
||||
exec("sc", "start", SERVICE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the barn service.
|
||||
*
|
||||
* @throws WindowsServiceException if the service fails to stop
|
||||
*/
|
||||
public void stop() {
|
||||
LOG.info("Stopping Windows service: {}", SERVICE_NAME);
|
||||
exec("sc", "stop", SERVICE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the barn service is installed.
|
||||
*
|
||||
* @return true if the service is installed
|
||||
*/
|
||||
public boolean isInstalled() {
|
||||
try {
|
||||
int exitCode = execWithExitCode("sc", "query", SERVICE_NAME);
|
||||
return exitCode == 0;
|
||||
} catch (WindowsServiceException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the barn service is running.
|
||||
*
|
||||
* @return true if the service is running
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
try {
|
||||
String output = execWithOutput("sc", "query", SERVICE_NAME);
|
||||
return output.contains("RUNNING");
|
||||
} catch (WindowsServiceException e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the current state of the service.
|
||||
*
|
||||
* @return the service state, or null if the service is not installed
|
||||
*/
|
||||
public ServiceState getState() {
|
||||
try {
|
||||
String output = execWithOutput("sc", "query", SERVICE_NAME);
|
||||
if (output.contains("RUNNING")) {
|
||||
return ServiceState.RUNNING;
|
||||
} else if (output.contains("STOPPED")) {
|
||||
return ServiceState.STOPPED;
|
||||
} else if (output.contains("START_PENDING")) {
|
||||
return ServiceState.START_PENDING;
|
||||
} else if (output.contains("STOP_PENDING")) {
|
||||
return ServiceState.STOP_PENDING;
|
||||
} else if (output.contains("PAUSED")) {
|
||||
return ServiceState.PAUSED;
|
||||
}
|
||||
return ServiceState.UNKNOWN;
|
||||
} catch (WindowsServiceException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void exec(String... args) {
|
||||
List<String> command = new ArrayList<>();
|
||||
for (String arg : args) {
|
||||
command.add(arg);
|
||||
}
|
||||
|
||||
int exitCode = execWithExitCode(command);
|
||||
if (exitCode != 0) {
|
||||
throw new WindowsServiceException("Command failed with exit code " + exitCode
|
||||
+ ": " + String.join(" ", command));
|
||||
}
|
||||
}
|
||||
|
||||
private int execWithExitCode(String... args) {
|
||||
List<String> command = new ArrayList<>();
|
||||
for (String arg : args) {
|
||||
command.add(arg);
|
||||
}
|
||||
return execWithExitCode(command);
|
||||
}
|
||||
|
||||
private int execWithExitCode(List<String> command) {
|
||||
try {
|
||||
ProcessBuilder pb = new ProcessBuilder(command);
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
|
||||
// Read output to prevent blocking
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
LOG.debug("sc: {}", line);
|
||||
}
|
||||
}
|
||||
|
||||
boolean completed = process.waitFor(COMMAND_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (!completed) {
|
||||
process.destroyForcibly();
|
||||
throw new WindowsServiceException("Command timed out: " + String.join(" ", command));
|
||||
}
|
||||
|
||||
return process.exitValue();
|
||||
} catch (IOException | InterruptedException e) {
|
||||
LOG.error("Failed to execute command: {}", String.join(" ", command), e);
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
throw new WindowsServiceException("Failed to execute command: " + String.join(" ", command), e);
|
||||
}
|
||||
}
|
||||
|
||||
private String execWithOutput(String... args) {
|
||||
List<String> command = new ArrayList<>();
|
||||
for (String arg : args) {
|
||||
command.add(arg);
|
||||
}
|
||||
|
||||
try {
|
||||
ProcessBuilder pb = new ProcessBuilder(command);
|
||||
pb.redirectErrorStream(true);
|
||||
Process process = pb.start();
|
||||
|
||||
StringBuilder output = new StringBuilder();
|
||||
try (BufferedReader reader = new BufferedReader(
|
||||
new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))) {
|
||||
String line;
|
||||
while ((line = reader.readLine()) != null) {
|
||||
output.append(line).append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
boolean completed = process.waitFor(COMMAND_TIMEOUT_SECONDS, TimeUnit.SECONDS);
|
||||
if (!completed) {
|
||||
process.destroyForcibly();
|
||||
throw new WindowsServiceException("Command timed out: " + String.join(" ", command));
|
||||
}
|
||||
|
||||
return output.toString();
|
||||
} catch (IOException | InterruptedException e) {
|
||||
LOG.error("Failed to execute command: {}", String.join(" ", command), e);
|
||||
if (e instanceof InterruptedException) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
throw new WindowsServiceException("Failed to execute command: " + String.join(" ", command), e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Windows service states.
|
||||
*/
|
||||
public enum ServiceState {
|
||||
/** Service is running. */
|
||||
RUNNING,
|
||||
/** Service is stopped. */
|
||||
STOPPED,
|
||||
/** Service is starting. */
|
||||
START_PENDING,
|
||||
/** Service is stopping. */
|
||||
STOP_PENDING,
|
||||
/** Service is paused. */
|
||||
PAUSED,
|
||||
/** Unknown state. */
|
||||
UNKNOWN
|
||||
}
|
||||
|
||||
/**
|
||||
* Exception thrown when a Windows service operation fails.
|
||||
*/
|
||||
public static class WindowsServiceException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
/**
|
||||
* Creates a new WindowsServiceException.
|
||||
*
|
||||
* @param message the error message
|
||||
*/
|
||||
public WindowsServiceException(String message) {
|
||||
super(message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a new WindowsServiceException with a cause.
|
||||
*
|
||||
* @param message the error message
|
||||
* @param cause the underlying cause
|
||||
*/
|
||||
public WindowsServiceException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
package com.samsonmedia.barn.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import com.samsonmedia.barn.config.Config;
|
||||
import com.samsonmedia.barn.config.JobsConfig;
|
||||
import com.samsonmedia.barn.execution.CrashRecovery;
|
||||
import com.samsonmedia.barn.execution.HeartbeatChecker;
|
||||
import com.samsonmedia.barn.execution.JobRunner;
|
||||
import com.samsonmedia.barn.execution.JobScheduler;
|
||||
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.state.BarnDirectories;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Main service daemon that orchestrates all barn components.
|
||||
*
|
||||
* <p>The service coordinates:
|
||||
* <ul>
|
||||
* <li>Job scheduling and execution</li>
|
||||
* <li>IPC server for CLI communication</li>
|
||||
* <li>Periodic cleanup of old jobs</li>
|
||||
* <li>Crash recovery on startup</li>
|
||||
* </ul>
|
||||
*/
|
||||
public class BarnService {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(BarnService.class);
|
||||
|
||||
private final Config config;
|
||||
private final BarnDirectories dirs;
|
||||
private final JobRepository repository;
|
||||
private final JobRunner runner;
|
||||
private final JobScheduler scheduler;
|
||||
private final CleanupScheduler cleanupScheduler;
|
||||
private final CrashRecovery crashRecovery;
|
||||
private final CountDownLatch shutdownLatch;
|
||||
private final AtomicBoolean running;
|
||||
private final ObjectMapper objectMapper;
|
||||
private IpcServer ipcServer;
|
||||
private Instant startedAt;
|
||||
|
||||
/**
|
||||
* Creates a new barn service.
|
||||
*
|
||||
* @param config the service configuration
|
||||
*/
|
||||
public BarnService(Config config) {
|
||||
this.config = Objects.requireNonNull(config, "config must not be null");
|
||||
this.dirs = new BarnDirectories(config.storage().baseDir());
|
||||
this.repository = new JobRepository(dirs);
|
||||
this.runner = new JobRunner(repository, dirs);
|
||||
this.scheduler = new JobScheduler(repository, runner, dirs, config);
|
||||
this.cleanupScheduler = new CleanupScheduler(repository, config.cleanup());
|
||||
|
||||
Duration heartbeatThreshold = Duration.ofSeconds(config.service().staleHeartbeatThresholdSeconds());
|
||||
HeartbeatChecker heartbeatChecker = new HeartbeatChecker(heartbeatThreshold);
|
||||
this.crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs);
|
||||
|
||||
this.shutdownLatch = new CountDownLatch(1);
|
||||
this.running = new AtomicBoolean(false);
|
||||
this.objectMapper = new ObjectMapper();
|
||||
this.objectMapper.registerModule(new JavaTimeModule());
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the service.
|
||||
*
|
||||
* @throws IOException if startup fails
|
||||
*/
|
||||
public void start() throws IOException {
|
||||
if (running.getAndSet(true)) {
|
||||
throw new IllegalStateException("Service already running");
|
||||
}
|
||||
|
||||
LOG.info("Starting Barn service");
|
||||
|
||||
// 1. Initialize directories
|
||||
dirs.initialize();
|
||||
LOG.debug("Initialized directories");
|
||||
|
||||
// 2. Run crash recovery
|
||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||
if (!recovered.isEmpty()) {
|
||||
LOG.info("Recovered {} orphaned jobs", recovered.size());
|
||||
}
|
||||
|
||||
// 3. Start scheduler
|
||||
scheduler.start();
|
||||
LOG.debug("Started job scheduler");
|
||||
|
||||
// 4. Start IPC server
|
||||
this.ipcServer = new IpcServer(config.service().ipcSocket(), this::handleIpcRequest);
|
||||
ipcServer.start();
|
||||
LOG.debug("Started IPC server on {}", config.service().ipcSocket());
|
||||
|
||||
// 5. Start cleanup scheduler (if enabled)
|
||||
if (config.cleanup().enabled()) {
|
||||
cleanupScheduler.start();
|
||||
LOG.debug("Started cleanup scheduler");
|
||||
}
|
||||
|
||||
startedAt = Instant.now();
|
||||
LOG.info("Barn service started");
|
||||
}
|
||||
|
||||
/**
|
||||
* Blocks until the service is stopped.
|
||||
*
|
||||
* @throws InterruptedException if interrupted while waiting
|
||||
*/
|
||||
public void awaitTermination() throws InterruptedException {
|
||||
shutdownLatch.await();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the service gracefully.
|
||||
*/
|
||||
public void stop() {
|
||||
if (!running.getAndSet(false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
LOG.info("Stopping Barn service");
|
||||
|
||||
// 1. Stop IPC server (reject new connections)
|
||||
if (ipcServer != null) {
|
||||
ipcServer.stop();
|
||||
LOG.debug("Stopped IPC server");
|
||||
}
|
||||
|
||||
// 2. Stop cleanup scheduler
|
||||
if (config.cleanup().enabled()) {
|
||||
cleanupScheduler.stop();
|
||||
LOG.debug("Stopped cleanup scheduler");
|
||||
}
|
||||
|
||||
// 3. Graceful scheduler stop (wait for running jobs)
|
||||
scheduler.stop();
|
||||
LOG.debug("Stopped job scheduler");
|
||||
|
||||
// 4. Signal shutdown complete
|
||||
shutdownLatch.countDown();
|
||||
|
||||
LOG.info("Barn service stopped");
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the service configuration.
|
||||
*
|
||||
* <p>Note: Some settings require a restart to take effect.
|
||||
*/
|
||||
public void reload() {
|
||||
LOG.info("Reloading configuration");
|
||||
// Currently, most config changes require restart
|
||||
// In the future, some settings could be applied dynamically
|
||||
LOG.info("Configuration reload complete (some changes require restart)");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the service is running.
|
||||
*
|
||||
* @return true if running
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
return running.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the service health status.
|
||||
*
|
||||
* @return the health status
|
||||
*/
|
||||
public ServiceHealth getHealth() {
|
||||
if (!running.get()) {
|
||||
return ServiceHealth.stopped();
|
||||
}
|
||||
|
||||
try {
|
||||
int active = repository.findByState(JobState.RUNNING).size();
|
||||
int queued = repository.findByState(JobState.QUEUED).size();
|
||||
return ServiceHealth.running(active, queued, startedAt);
|
||||
} catch (IOException e) {
|
||||
LOG.error("Failed to get health status: {}", e.getMessage());
|
||||
return ServiceHealth.running(0, 0, startedAt);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the job repository.
|
||||
*
|
||||
* @return the repository
|
||||
*/
|
||||
public JobRepository getRepository() {
|
||||
return repository;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the job scheduler.
|
||||
*
|
||||
* @return the scheduler
|
||||
*/
|
||||
public JobScheduler getScheduler() {
|
||||
return scheduler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the service directories.
|
||||
*
|
||||
* @return the directories
|
||||
*/
|
||||
public BarnDirectories getDirectories() {
|
||||
return dirs;
|
||||
}
|
||||
|
||||
private Object handleIpcRequest(String type, Object payload) throws IpcException {
|
||||
LOG.debug("Handling IPC request: {}", type);
|
||||
|
||||
try {
|
||||
return switch (type) {
|
||||
case "get_service_status" -> getHealth();
|
||||
case "shutdown" -> {
|
||||
// Schedule shutdown in background
|
||||
new Thread(this::stop, "shutdown").start();
|
||||
yield "Shutdown initiated";
|
||||
}
|
||||
case "reload" -> {
|
||||
reload();
|
||||
yield "Configuration reloaded";
|
||||
}
|
||||
case "get_status" -> handleGetStatus(payload);
|
||||
case "get_job" -> handleGetJob(payload);
|
||||
case "run_job" -> handleRunJob(payload);
|
||||
case "kill_job" -> handleKillJob(payload);
|
||||
case "clean_jobs" -> handleCleanJobs(payload);
|
||||
default -> throw new IpcException("INVALID_REQUEST", "Unknown request type: " + type);
|
||||
};
|
||||
} catch (IOException e) {
|
||||
throw new IpcException("INTERNAL_ERROR", "Failed to process request: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private Object handleGetStatus(Object payload) throws IOException {
|
||||
String tag = null;
|
||||
JobState state = null;
|
||||
Integer limit = null;
|
||||
|
||||
if (payload instanceof java.util.Map<?, ?> map) {
|
||||
tag = (String) map.get("tag");
|
||||
String stateStr = (String) map.get("state");
|
||||
if (stateStr != null) {
|
||||
state = JobState.valueOf(stateStr.toUpperCase());
|
||||
}
|
||||
limit = (Integer) map.get("limit");
|
||||
}
|
||||
|
||||
List<Job> jobs = repository.findAll();
|
||||
LOG.info("IPC get_status: found {} jobs", jobs.size());
|
||||
|
||||
// Apply filters
|
||||
final String filterTag = tag;
|
||||
final JobState filterState = state;
|
||||
jobs = jobs.stream()
|
||||
.filter(job -> filterTag == null || filterTag.equals(job.tag()))
|
||||
.filter(job -> filterState == null || filterState == job.state())
|
||||
.sorted((a, b) -> b.createdAt().compareTo(a.createdAt()))
|
||||
.toList();
|
||||
|
||||
if (limit != null && limit > 0 && jobs.size() > limit) {
|
||||
jobs = jobs.subList(0, limit);
|
||||
}
|
||||
|
||||
return jobs;
|
||||
}
|
||||
|
||||
private Object handleGetJob(Object payload) throws IOException, IpcException {
|
||||
final String jobId;
|
||||
|
||||
if (payload instanceof java.util.Map<?, ?> map) {
|
||||
jobId = (String) map.get("jobId");
|
||||
} else if (payload instanceof String) {
|
||||
jobId = (String) payload;
|
||||
} else {
|
||||
jobId = null;
|
||||
}
|
||||
|
||||
if (jobId == null) {
|
||||
throw new IpcException("INVALID_REQUEST", "Job ID is required");
|
||||
}
|
||||
|
||||
return repository.findById(jobId)
|
||||
.orElseThrow(() -> new IpcException("NOT_FOUND", "Job not found: " + jobId));
|
||||
}
|
||||
|
||||
private Object handleRunJob(Object payload) throws IOException, IpcException {
|
||||
if (!(payload instanceof java.util.Map<?, ?> map)) {
|
||||
throw new IpcException("INVALID_REQUEST", "Invalid payload");
|
||||
}
|
||||
|
||||
@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");
|
||||
|
||||
if (command == null || command.isEmpty()) {
|
||||
throw new IpcException("INVALID_REQUEST", "Command is required");
|
||||
}
|
||||
|
||||
JobsConfig jobsConfig = config.jobs();
|
||||
if (maxRetries != null || retryDelaySeconds != null) {
|
||||
jobsConfig = new JobsConfig(
|
||||
jobsConfig.defaultTimeoutSeconds(),
|
||||
maxRetries != null ? maxRetries : jobsConfig.maxRetries(),
|
||||
retryDelaySeconds != null ? retryDelaySeconds : jobsConfig.retryDelaySeconds(),
|
||||
jobsConfig.retryBackoffMultiplier(),
|
||||
jobsConfig.retryOnExitCodes()
|
||||
);
|
||||
}
|
||||
|
||||
Job job = repository.create(command, tag, jobsConfig);
|
||||
LOG.info("Created job via IPC: {}", job.id());
|
||||
return job;
|
||||
}
|
||||
|
||||
private Object handleKillJob(Object payload) throws IOException, IpcException {
|
||||
final String jobId;
|
||||
final boolean forceKill;
|
||||
|
||||
if (payload instanceof java.util.Map<?, ?> map) {
|
||||
jobId = (String) map.get("jobId");
|
||||
forceKill = Boolean.TRUE.equals(map.get("force"));
|
||||
} else if (payload instanceof String) {
|
||||
jobId = (String) payload;
|
||||
forceKill = false;
|
||||
} else {
|
||||
jobId = null;
|
||||
forceKill = false;
|
||||
}
|
||||
|
||||
if (jobId == null) {
|
||||
throw new IpcException("INVALID_REQUEST", "Job ID is required");
|
||||
}
|
||||
|
||||
Job job = repository.findById(jobId)
|
||||
.orElseThrow(() -> new IpcException("NOT_FOUND", "Job not found: " + jobId));
|
||||
|
||||
if (job.state() != JobState.RUNNING) {
|
||||
throw new IpcException("INVALID_STATE", "Job is not running: " + job.state());
|
||||
}
|
||||
|
||||
// Kill the process
|
||||
if (job.pid() != null) {
|
||||
ProcessHandle.of(job.pid()).ifPresent(ph -> {
|
||||
if (forceKill) {
|
||||
ph.destroyForcibly();
|
||||
} else {
|
||||
ph.destroy();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Update job state
|
||||
repository.updateState(jobId, JobState.CANCELED);
|
||||
LOG.info("Killed job via IPC: {} (force={})", jobId, forceKill);
|
||||
|
||||
return repository.findById(jobId).orElse(job);
|
||||
}
|
||||
|
||||
private Object handleCleanJobs(Object payload) throws IOException {
|
||||
final boolean includeFailed;
|
||||
final boolean dryRun;
|
||||
final String jobId;
|
||||
|
||||
if (payload instanceof java.util.Map<?, ?> map) {
|
||||
includeFailed = Boolean.TRUE.equals(map.get("includeFailed"));
|
||||
dryRun = Boolean.TRUE.equals(map.get("dryRun"));
|
||||
jobId = (String) map.get("jobId");
|
||||
} else {
|
||||
includeFailed = false;
|
||||
dryRun = false;
|
||||
jobId = null;
|
||||
}
|
||||
|
||||
List<Job> toClean;
|
||||
|
||||
if (jobId != null) {
|
||||
toClean = repository.findById(jobId)
|
||||
.filter(j -> j.state() == JobState.SUCCEEDED
|
||||
|| includeFailed && j.state() == JobState.FAILED
|
||||
|| j.state() == JobState.CANCELED)
|
||||
.map(List::of)
|
||||
.orElse(List.of());
|
||||
} else {
|
||||
toClean = repository.findAll().stream()
|
||||
.filter(j -> j.state() == JobState.SUCCEEDED
|
||||
|| includeFailed && j.state() == JobState.FAILED
|
||||
|| j.state() == JobState.CANCELED)
|
||||
.toList();
|
||||
}
|
||||
|
||||
if (!dryRun) {
|
||||
for (Job job : toClean) {
|
||||
repository.delete(job.id());
|
||||
LOG.info("Cleaned job via IPC: {}", job.id());
|
||||
}
|
||||
}
|
||||
|
||||
return java.util.Map.of(
|
||||
"cleaned", toClean.size(),
|
||||
"dryRun", dryRun,
|
||||
"jobs", toClean
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
package com.samsonmedia.barn.service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.samsonmedia.barn.config.CleanupConfig;
|
||||
import com.samsonmedia.barn.jobs.Job;
|
||||
import com.samsonmedia.barn.jobs.JobRepository;
|
||||
import com.samsonmedia.barn.state.JobState;
|
||||
|
||||
/**
|
||||
* Scheduler for periodic cleanup of old completed jobs.
|
||||
*/
|
||||
public class CleanupScheduler {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(CleanupScheduler.class);
|
||||
|
||||
private final JobRepository repository;
|
||||
private final CleanupConfig config;
|
||||
private final ScheduledExecutorService executor;
|
||||
private final AtomicBoolean running;
|
||||
|
||||
/**
|
||||
* Creates a cleanup scheduler.
|
||||
*
|
||||
* @param repository the job repository
|
||||
* @param config the cleanup configuration
|
||||
*/
|
||||
public CleanupScheduler(JobRepository repository, CleanupConfig config) {
|
||||
this.repository = Objects.requireNonNull(repository, "repository must not be null");
|
||||
this.config = Objects.requireNonNull(config, "config must not be null");
|
||||
this.executor = Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "cleanup-scheduler");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
this.running = new AtomicBoolean(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the cleanup scheduler.
|
||||
*/
|
||||
public void start() {
|
||||
if (running.getAndSet(true)) {
|
||||
throw new IllegalStateException("Cleanup scheduler already running");
|
||||
}
|
||||
|
||||
Duration interval = Duration.ofMinutes(config.cleanupIntervalMinutes());
|
||||
LOG.info("Starting cleanup scheduler with interval: {} minutes", config.cleanupIntervalMinutes());
|
||||
|
||||
executor.scheduleAtFixedRate(
|
||||
this::runCleanup,
|
||||
interval.toMinutes(),
|
||||
interval.toMinutes(),
|
||||
TimeUnit.MINUTES
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the cleanup scheduler.
|
||||
*/
|
||||
public void stop() {
|
||||
if (!running.getAndSet(false)) {
|
||||
return;
|
||||
}
|
||||
|
||||
LOG.info("Stopping cleanup scheduler");
|
||||
executor.shutdownNow();
|
||||
|
||||
try {
|
||||
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
LOG.warn("Cleanup scheduler did not terminate gracefully");
|
||||
}
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
LOG.warn("Interrupted while stopping cleanup scheduler");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the scheduler is running.
|
||||
*
|
||||
* @return true if running
|
||||
*/
|
||||
public boolean isRunning() {
|
||||
return running.get();
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs cleanup immediately (for testing).
|
||||
*/
|
||||
public void runNow() {
|
||||
runCleanup();
|
||||
}
|
||||
|
||||
private void runCleanup() {
|
||||
LOG.debug("Running cleanup");
|
||||
|
||||
try {
|
||||
List<Job> jobs = repository.findAll();
|
||||
int cleaned = 0;
|
||||
|
||||
for (Job job : jobs) {
|
||||
if (shouldClean(job)) {
|
||||
repository.delete(job.id());
|
||||
cleaned++;
|
||||
LOG.debug("Cleaned job: {}", job.id());
|
||||
}
|
||||
}
|
||||
|
||||
if (cleaned > 0) {
|
||||
LOG.info("Cleaned {} jobs", cleaned);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
LOG.error("Cleanup failed: {}", e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean shouldClean(Job job) {
|
||||
// Never clean active jobs
|
||||
if (job.state() == JobState.RUNNING || job.state() == JobState.QUEUED) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Instant finished = job.finishedAt();
|
||||
if (finished == null) {
|
||||
finished = job.createdAt();
|
||||
}
|
||||
|
||||
Duration age = Duration.between(finished, Instant.now());
|
||||
Duration maxAge;
|
||||
|
||||
if (job.state() == JobState.FAILED && config.keepFailedJobs()) {
|
||||
maxAge = Duration.ofHours(config.keepFailedJobsHours());
|
||||
} else {
|
||||
maxAge = Duration.ofHours(config.maxAgeHours());
|
||||
}
|
||||
|
||||
return age.compareTo(maxAge) > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.samsonmedia.barn.service;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* Health status of the barn service.
|
||||
*
|
||||
* @param running whether the service is running
|
||||
* @param activeJobs number of currently running jobs
|
||||
* @param queuedJobs number of jobs waiting to run
|
||||
* @param startedAt when the service was started
|
||||
* @param uptimeSeconds how long the service has been running
|
||||
*/
|
||||
public record ServiceHealth(
|
||||
boolean running,
|
||||
int activeJobs,
|
||||
int queuedJobs,
|
||||
Instant startedAt,
|
||||
long uptimeSeconds
|
||||
) {
|
||||
|
||||
/**
|
||||
* Creates a health record for a running service.
|
||||
*
|
||||
* @param activeJobs number of active jobs
|
||||
* @param queuedJobs number of queued jobs
|
||||
* @param startedAt when service started
|
||||
* @return the health record
|
||||
*/
|
||||
public static ServiceHealth running(int activeJobs, int queuedJobs, Instant startedAt) {
|
||||
long uptime = Duration.between(startedAt, Instant.now()).getSeconds();
|
||||
return new ServiceHealth(true, activeJobs, queuedJobs, startedAt, uptime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a health record for a stopped service.
|
||||
*
|
||||
* @return the health record
|
||||
*/
|
||||
public static ServiceHealth stopped() {
|
||||
return new ServiceHealth(false, 0, 0, null, 0);
|
||||
}
|
||||
}
|
||||
@@ -168,6 +168,15 @@ public final class BarnDirectories {
|
||||
return getLogsDir().resolve("barn.log");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the IPC socket file path.
|
||||
*
|
||||
* @return the socket file path
|
||||
*/
|
||||
public Path getSocketPath() {
|
||||
return baseDir.resolve("barn.sock");
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the top-level directory structure.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package com.samsonmedia.barn.util;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* Utility for parsing human-readable duration strings.
|
||||
*
|
||||
* <p>Supports formats like:
|
||||
* <ul>
|
||||
* <li>30m - 30 minutes</li>
|
||||
* <li>24h - 24 hours</li>
|
||||
* <li>7d - 7 days</li>
|
||||
* <li>2w - 2 weeks</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class DurationParser {
|
||||
|
||||
private static final Pattern DURATION_PATTERN = Pattern.compile("^(\\d+)([mhdwMHDW])$");
|
||||
|
||||
private DurationParser() {
|
||||
// Utility class - prevent instantiation
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a duration string into a Duration.
|
||||
*
|
||||
* @param input the duration string (e.g., "24h", "7d")
|
||||
* @return the parsed Duration
|
||||
* @throws IllegalArgumentException if the input is invalid
|
||||
*/
|
||||
public static Duration parse(String input) {
|
||||
if (input == null || input.isBlank()) {
|
||||
throw new IllegalArgumentException("Duration cannot be null or empty");
|
||||
}
|
||||
|
||||
String trimmed = input.trim();
|
||||
Matcher matcher = DURATION_PATTERN.matcher(trimmed);
|
||||
|
||||
if (!matcher.matches()) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid duration format: '" + input + "'. Expected format: <number><unit> "
|
||||
+ "(e.g., 30m, 24h, 7d, 2w)");
|
||||
}
|
||||
|
||||
long value = Long.parseLong(matcher.group(1));
|
||||
String unit = matcher.group(2).toLowerCase();
|
||||
|
||||
if (value <= 0) {
|
||||
throw new IllegalArgumentException("Duration value must be positive: " + value);
|
||||
}
|
||||
|
||||
return switch (unit) {
|
||||
case "m" -> Duration.ofMinutes(value);
|
||||
case "h" -> Duration.ofHours(value);
|
||||
case "d" -> Duration.ofDays(value);
|
||||
case "w" -> Duration.ofDays(value * 7);
|
||||
default -> throw new IllegalArgumentException("Invalid duration unit: " + unit);
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
<configuration>
|
||||
<!-- Console appender for development/foreground -->
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- File appender for daemon mode -->
|
||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${BARN_LOG_DIR:-${java.io.tmpdir}/barn/logs}/barn.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${BARN_LOG_DIR:-${java.io.tmpdir}/barn/logs}/barn.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
|
||||
<maxFileSize>10MB</maxFileSize>
|
||||
<maxHistory>7</maxHistory>
|
||||
<totalSizeCap>100MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{ISO8601} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- JSON appender for structured logging -->
|
||||
<appender name="JSON" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>${BARN_LOG_DIR:-${java.io.tmpdir}/barn/logs}/barn.json.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
|
||||
<fileNamePattern>${BARN_LOG_DIR:-${java.io.tmpdir}/barn/logs}/barn.json.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
|
||||
<maxFileSize>10MB</maxFileSize>
|
||||
<maxHistory>7</maxHistory>
|
||||
</rollingPolicy>
|
||||
<encoder class="net.logstash.logback.encoder.LogstashEncoder">
|
||||
<includeMdcKeyName>jobId</includeMdcKeyName>
|
||||
<includeMdcKeyName>jobTag</includeMdcKeyName>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<root level="${BARN_LOG_LEVEL:-INFO}">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="FILE"/>
|
||||
</root>
|
||||
</configuration>
|
||||
Reference in new issue
Block a user