Archived
feat(state): implement filesystem state management system (#3)
- Add AtomicFiles utility for atomic file operations (write-to-tmp-then-rename) - Add JobState enum (queued, running, succeeded, failed, canceled) - Create BarnDirectories for managing directory structure: - jobs/, locks/, logs/ top-level directories - Per-job: work/input/, work/output/, logs/ subdirectories - Lock files for scheduler and individual jobs - Implement StateFiles for reading/writing job metadata: - State, tag, timestamps (created_at, started_at, finished_at, heartbeat) - Exit codes (integer and symbolic), error messages - PID, retry count, retry history, stage - All timestamps in ISO-8601 format - Add FileLock for cross-process file locking using FileChannel.tryLock() - Handle OverlappingFileLockException for same-JVM lock attempts - Add comprehensive tests (92 new tests, 211 total) Closes #3 Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
79f89be47c
commit
647e602fe9
10 files changed
+1917
No files matched your search
@@ -0,0 +1,120 @@
|
||||
package com.samsonmedia.barn.state;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.NoSuchFileException;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.StandardCopyOption;
|
||||
import java.nio.file.StandardOpenOption;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* Utility class for atomic file operations.
|
||||
*
|
||||
* <p>Atomic writes work by writing to a temporary file first, then atomically
|
||||
* renaming it to the target. This ensures that readers never see partial content.
|
||||
*/
|
||||
public final class AtomicFiles {
|
||||
|
||||
private static final String TMP_SUFFIX = ".tmp";
|
||||
|
||||
private AtomicFiles() {
|
||||
// Utility class - prevent instantiation
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes content to a file atomically.
|
||||
*
|
||||
* <p>The content is first written to a temporary file, then atomically
|
||||
* renamed to the target path. This ensures that the target file either
|
||||
* contains the complete content or doesn't exist.
|
||||
*
|
||||
* @param target the target file path
|
||||
* @param content the content to write
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public static void writeAtomically(Path target, String content) throws IOException {
|
||||
Objects.requireNonNull(target, "target must not be null");
|
||||
Objects.requireNonNull(content, "content must not be null");
|
||||
|
||||
Path tempFile = target.resolveSibling(target.getFileName() + TMP_SUFFIX);
|
||||
|
||||
try {
|
||||
Files.writeString(tempFile, content,
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.TRUNCATE_EXISTING,
|
||||
StandardOpenOption.WRITE);
|
||||
|
||||
Files.move(tempFile, target,
|
||||
StandardCopyOption.ATOMIC_MOVE,
|
||||
StandardCopyOption.REPLACE_EXISTING);
|
||||
} catch (IOException e) {
|
||||
// Clean up temp file on failure
|
||||
try {
|
||||
Files.deleteIfExists(tempFile);
|
||||
} catch (IOException ignored) {
|
||||
// Best effort cleanup
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads content from a file safely.
|
||||
*
|
||||
* <p>Returns an empty Optional if the file doesn't exist, rather than
|
||||
* throwing an exception. The content is trimmed of leading/trailing whitespace.
|
||||
*
|
||||
* @param path the file to read
|
||||
* @return the file content, or empty if the file doesn't exist
|
||||
* @throws IOException if reading fails for reasons other than file not found
|
||||
*/
|
||||
public static Optional<String> readSafely(Path path) throws IOException {
|
||||
Objects.requireNonNull(path, "path must not be null");
|
||||
|
||||
try {
|
||||
String content = Files.readString(path);
|
||||
return Optional.of(content.trim());
|
||||
} catch (NoSuchFileException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads content from a file, returning empty string if not found.
|
||||
*
|
||||
* @param path the file to read
|
||||
* @return the file content, or empty string if the file doesn't exist
|
||||
* @throws IOException if reading fails for reasons other than file not found
|
||||
*/
|
||||
public static String readOrEmpty(Path path) throws IOException {
|
||||
return readSafely(path).orElse("");
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes a file if it exists.
|
||||
*
|
||||
* @param path the file to delete
|
||||
* @return true if the file was deleted, false if it didn't exist
|
||||
* @throws IOException if deletion fails
|
||||
*/
|
||||
public static boolean deleteIfExists(Path path) throws IOException {
|
||||
Objects.requireNonNull(path, "path must not be null");
|
||||
return Files.deleteIfExists(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates parent directories for a file if they don't exist.
|
||||
*
|
||||
* @param path the file path
|
||||
* @throws IOException if directory creation fails
|
||||
*/
|
||||
public static void ensureParentDirectories(Path path) throws IOException {
|
||||
Objects.requireNonNull(path, "path must not be null");
|
||||
Path parent = path.getParent();
|
||||
if (parent != null && !Files.exists(parent)) {
|
||||
Files.createDirectories(parent);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,233 @@
|
||||
package com.samsonmedia.barn.state;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* Manages the Barn directory structure.
|
||||
*
|
||||
* <p>The directory layout is:
|
||||
* <pre>
|
||||
* {baseDir}/
|
||||
* jobs/
|
||||
* {jobId}/
|
||||
* work/
|
||||
* input/
|
||||
* output/
|
||||
* logs/
|
||||
* locks/
|
||||
* logs/
|
||||
* </pre>
|
||||
*/
|
||||
public final class BarnDirectories {
|
||||
|
||||
/** Subdirectory for job data. */
|
||||
public static final String JOBS_DIR = "jobs";
|
||||
|
||||
/** Subdirectory for lock files. */
|
||||
public static final String LOCKS_DIR = "locks";
|
||||
|
||||
/** Subdirectory for daemon logs. */
|
||||
public static final String LOGS_DIR = "logs";
|
||||
|
||||
/** Subdirectory for job working files. */
|
||||
public static final String WORK_DIR = "work";
|
||||
|
||||
/** Subdirectory for input files within work. */
|
||||
public static final String INPUT_DIR = "input";
|
||||
|
||||
/** Subdirectory for output files within work. */
|
||||
public static final String OUTPUT_DIR = "output";
|
||||
|
||||
private final Path baseDir;
|
||||
|
||||
/**
|
||||
* Creates a BarnDirectories instance with the specified base directory.
|
||||
*
|
||||
* @param baseDir the base directory for all Barn data
|
||||
*/
|
||||
public BarnDirectories(Path baseDir) {
|
||||
this.baseDir = Objects.requireNonNull(baseDir, "baseDir must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the base directory.
|
||||
*
|
||||
* @return the base directory path
|
||||
*/
|
||||
public Path getBaseDir() {
|
||||
return baseDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the jobs directory.
|
||||
*
|
||||
* @return the jobs directory path
|
||||
*/
|
||||
public Path getJobsDir() {
|
||||
return baseDir.resolve(JOBS_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the locks directory.
|
||||
*
|
||||
* @return the locks directory path
|
||||
*/
|
||||
public Path getLocksDir() {
|
||||
return baseDir.resolve(LOCKS_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the daemon logs directory.
|
||||
*
|
||||
* @return the logs directory path
|
||||
*/
|
||||
public Path getLogsDir() {
|
||||
return baseDir.resolve(LOGS_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the directory for a specific job.
|
||||
*
|
||||
* @param jobId the job identifier
|
||||
* @return the job directory path
|
||||
*/
|
||||
public Path getJobDir(String jobId) {
|
||||
Objects.requireNonNull(jobId, "jobId must not be null");
|
||||
return getJobsDir().resolve(jobId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the working directory for a specific job.
|
||||
*
|
||||
* @param jobId the job identifier
|
||||
* @return the job work directory path
|
||||
*/
|
||||
public Path getJobWorkDir(String jobId) {
|
||||
return getJobDir(jobId).resolve(WORK_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the input directory for a specific job.
|
||||
*
|
||||
* @param jobId the job identifier
|
||||
* @return the job input directory path
|
||||
*/
|
||||
public Path getJobInputDir(String jobId) {
|
||||
return getJobWorkDir(jobId).resolve(INPUT_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the output directory for a specific job.
|
||||
*
|
||||
* @param jobId the job identifier
|
||||
* @return the job output directory path
|
||||
*/
|
||||
public Path getJobOutputDir(String jobId) {
|
||||
return getJobWorkDir(jobId).resolve(OUTPUT_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the logs directory for a specific job.
|
||||
*
|
||||
* @param jobId the job identifier
|
||||
* @return the job logs directory path
|
||||
*/
|
||||
public Path getJobLogsDir(String jobId) {
|
||||
return getJobDir(jobId).resolve(LOGS_DIR);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the lock file path for a specific job.
|
||||
*
|
||||
* @param jobId the job identifier
|
||||
* @return the job lock file path
|
||||
*/
|
||||
public Path getJobLockFile(String jobId) {
|
||||
Objects.requireNonNull(jobId, "jobId must not be null");
|
||||
return getLocksDir().resolve("job-" + jobId + ".lock");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the scheduler lock file path.
|
||||
*
|
||||
* @return the scheduler lock file path
|
||||
*/
|
||||
public Path getSchedulerLockFile() {
|
||||
return getLocksDir().resolve("scheduler.lock");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the daemon log file path.
|
||||
*
|
||||
* @return the daemon log file path
|
||||
*/
|
||||
public Path getDaemonLogFile() {
|
||||
return getLogsDir().resolve("barn.log");
|
||||
}
|
||||
|
||||
/**
|
||||
* Initializes the top-level directory structure.
|
||||
*
|
||||
* <p>Creates the base directory and all subdirectories if they don't exist.
|
||||
*
|
||||
* @throws IOException if directory creation fails
|
||||
*/
|
||||
public void initialize() throws IOException {
|
||||
Files.createDirectories(getJobsDir());
|
||||
Files.createDirectories(getLocksDir());
|
||||
Files.createDirectories(getLogsDir());
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the directory structure for a specific job.
|
||||
*
|
||||
* @param jobId the job identifier
|
||||
* @throws IOException if directory creation fails
|
||||
*/
|
||||
public void createJobDirs(String jobId) throws IOException {
|
||||
Objects.requireNonNull(jobId, "jobId must not be null");
|
||||
Files.createDirectories(getJobDir(jobId));
|
||||
Files.createDirectories(getJobInputDir(jobId));
|
||||
Files.createDirectories(getJobOutputDir(jobId));
|
||||
Files.createDirectories(getJobLogsDir(jobId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a job directory exists.
|
||||
*
|
||||
* @param jobId the job identifier
|
||||
* @return true if the job directory exists
|
||||
*/
|
||||
public boolean jobExists(String jobId) {
|
||||
Objects.requireNonNull(jobId, "jobId must not be null");
|
||||
return Files.exists(getJobDir(jobId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Deletes the directory for a specific job.
|
||||
*
|
||||
* @param jobId the job identifier
|
||||
* @throws IOException if deletion fails
|
||||
*/
|
||||
public void deleteJobDir(String jobId) throws IOException {
|
||||
Objects.requireNonNull(jobId, "jobId must not be null");
|
||||
Path jobDir = getJobDir(jobId);
|
||||
if (Files.exists(jobDir)) {
|
||||
deleteRecursively(jobDir);
|
||||
}
|
||||
}
|
||||
|
||||
private void deleteRecursively(Path path) throws IOException {
|
||||
if (Files.isDirectory(path)) {
|
||||
try (var stream = Files.list(path)) {
|
||||
for (Path child : stream.toList()) {
|
||||
deleteRecursively(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
Files.delete(path);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package com.samsonmedia.barn.state;
|
||||
|
||||
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;
|
||||
|
||||
/**
|
||||
* A file-based lock for coordinating access to resources.
|
||||
*
|
||||
* <p>Uses {@link FileChannel#tryLock()} for cross-process locking.
|
||||
* The lock is released when the FileLock is closed.
|
||||
*/
|
||||
public final class FileLock implements AutoCloseable {
|
||||
|
||||
private static final Logger LOG = LoggerFactory.getLogger(FileLock.class);
|
||||
|
||||
private final Path lockFile;
|
||||
private final FileChannel channel;
|
||||
private final java.nio.channels.FileLock lock;
|
||||
|
||||
private FileLock(Path lockFile, FileChannel channel, java.nio.channels.FileLock lock) {
|
||||
this.lockFile = lockFile;
|
||||
this.channel = channel;
|
||||
this.lock = lock;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempts to acquire a lock on the specified file.
|
||||
*
|
||||
* <p>This is a non-blocking operation. If the lock cannot be acquired
|
||||
* (because another process holds it), this method returns an empty Optional.
|
||||
*
|
||||
* @param lockFile the path to the lock file
|
||||
* @return the acquired lock, or empty if the lock is already held
|
||||
* @throws IOException if lock file creation or acquisition fails
|
||||
*/
|
||||
public static Optional<FileLock> 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 = null;
|
||||
try {
|
||||
channel = FileChannel.open(lockFile,
|
||||
StandardOpenOption.CREATE,
|
||||
StandardOpenOption.WRITE);
|
||||
|
||||
java.nio.channels.FileLock lock;
|
||||
try {
|
||||
lock = channel.tryLock();
|
||||
} catch (OverlappingFileLockException e) {
|
||||
// Lock is held by another thread in this JVM
|
||||
channel.close();
|
||||
LOG.debug("Could not acquire lock (held by same JVM): {}", lockFile);
|
||||
return Optional.empty();
|
||||
}
|
||||
if (lock == null) {
|
||||
// Lock is held by another process
|
||||
channel.close();
|
||||
LOG.debug("Could not acquire lock: {}", lockFile);
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
LOG.debug("Acquired lock: {}", lockFile);
|
||||
return Optional.of(new FileLock(lockFile, channel, lock));
|
||||
|
||||
} catch (IOException e) {
|
||||
if (channel != null) {
|
||||
try {
|
||||
channel.close();
|
||||
} catch (IOException ignored) {
|
||||
// Best effort cleanup
|
||||
}
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a lock file is currently locked by another process.
|
||||
*
|
||||
* <p>This method tries to acquire the lock temporarily. If it succeeds,
|
||||
* the lock is immediately released, indicating no one else holds it.
|
||||
*
|
||||
* @param lockFile the path to the lock file
|
||||
* @return true if the lock is held by another process, false otherwise
|
||||
*/
|
||||
public static boolean isLocked(Path lockFile) {
|
||||
Objects.requireNonNull(lockFile, "lockFile must not be null");
|
||||
|
||||
if (!Files.exists(lockFile)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try (FileLock lock = tryAcquire(lockFile).orElse(null)) {
|
||||
if (lock == null) {
|
||||
return true; // Couldn't acquire, so it's locked
|
||||
}
|
||||
return false; // Acquired and released, so it wasn't locked
|
||||
} catch (IOException e) {
|
||||
LOG.debug("Error checking lock status: {}", e.getMessage());
|
||||
return false; // Assume not locked on error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the lock file path.
|
||||
*
|
||||
* @return the lock file path
|
||||
*/
|
||||
public Path getLockFile() {
|
||||
return lockFile;
|
||||
}
|
||||
|
||||
/**
|
||||
* Releases the lock and closes the file channel.
|
||||
*
|
||||
* <p>The lock file is deleted after the lock is released.
|
||||
*/
|
||||
@Override
|
||||
public void close() throws IOException {
|
||||
try {
|
||||
if (lock.isValid()) {
|
||||
lock.release();
|
||||
LOG.debug("Released lock: {}", lockFile);
|
||||
}
|
||||
} finally {
|
||||
channel.close();
|
||||
// Try to delete the lock file, but don't fail if it doesn't work
|
||||
try {
|
||||
Files.deleteIfExists(lockFile);
|
||||
} catch (IOException e) {
|
||||
LOG.debug("Could not delete lock file: {}", lockFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.samsonmedia.barn.state;
|
||||
|
||||
/**
|
||||
* Represents the current state of a job in its lifecycle.
|
||||
*/
|
||||
public enum JobState {
|
||||
/** Job is waiting to be executed. */
|
||||
QUEUED,
|
||||
|
||||
/** Job is currently running. */
|
||||
RUNNING,
|
||||
|
||||
/** Job completed successfully. */
|
||||
SUCCEEDED,
|
||||
|
||||
/** Job failed to complete. */
|
||||
FAILED,
|
||||
|
||||
/** Job was manually canceled. */
|
||||
CANCELED;
|
||||
|
||||
/**
|
||||
* Parses a job state from a string (case-insensitive).
|
||||
*
|
||||
* @param value the string value to parse
|
||||
* @return the parsed JobState
|
||||
* @throws IllegalArgumentException if the value is not a valid state
|
||||
*/
|
||||
public static JobState fromString(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
throw new IllegalArgumentException("Job state cannot be null or blank");
|
||||
}
|
||||
try {
|
||||
return valueOf(value.trim().toUpperCase());
|
||||
} catch (IllegalArgumentException e) {
|
||||
throw new IllegalArgumentException(
|
||||
"Invalid job state: '" + value + "'. Valid values are: queued, running, succeeded, failed, canceled");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the lowercase string representation.
|
||||
*
|
||||
* @return the state name in lowercase
|
||||
*/
|
||||
public String toLowercase() {
|
||||
return name().toLowerCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if this is a terminal state (job is finished).
|
||||
*
|
||||
* @return true if the job is in a terminal state
|
||||
*/
|
||||
public boolean isTerminal() {
|
||||
return this == SUCCEEDED || this == FAILED || this == CANCELED;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if this is an active state (job is not finished).
|
||||
*
|
||||
* @return true if the job is active
|
||||
*/
|
||||
public boolean isActive() {
|
||||
return !isTerminal();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,446 @@
|
||||
package com.samsonmedia.barn.state;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Path;
|
||||
import java.time.Instant;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Objects;
|
||||
import java.util.Optional;
|
||||
import java.util.OptionalInt;
|
||||
import java.util.OptionalLong;
|
||||
|
||||
/**
|
||||
* Manages state files for a job directory.
|
||||
*
|
||||
* <p>State files are plain-text files containing job metadata and lifecycle information.
|
||||
* All writes are atomic to ensure consistency.
|
||||
*/
|
||||
public final class StateFiles {
|
||||
|
||||
/** State file name. */
|
||||
public static final String STATE = "state";
|
||||
|
||||
/** Tag file name. */
|
||||
public static final String TAG = "tag";
|
||||
|
||||
/** Created timestamp file name. */
|
||||
public static final String CREATED_AT = "created_at";
|
||||
|
||||
/** Started timestamp file name. */
|
||||
public static final String STARTED_AT = "started_at";
|
||||
|
||||
/** Finished timestamp file name. */
|
||||
public static final String FINISHED_AT = "finished_at";
|
||||
|
||||
/** Exit code file name. */
|
||||
public static final String EXIT_CODE = "exit_code";
|
||||
|
||||
/** Error message file name. */
|
||||
public static final String ERROR = "error";
|
||||
|
||||
/** Process ID file name. */
|
||||
public static final String PID = "pid";
|
||||
|
||||
/** Heartbeat timestamp file name. */
|
||||
public static final String HEARTBEAT = "heartbeat";
|
||||
|
||||
/** Retry count file name. */
|
||||
public static final String RETRY_COUNT = "retry_count";
|
||||
|
||||
/** Retry timestamp file name. */
|
||||
public static final String RETRY_AT = "retry_at";
|
||||
|
||||
/** Retry history file name. */
|
||||
public static final String RETRY_HISTORY = "retry_history";
|
||||
|
||||
/** Stage file name. */
|
||||
public static final String STAGE = "stage";
|
||||
|
||||
private final Path jobDir;
|
||||
|
||||
/**
|
||||
* Creates a StateFiles instance for the specified job directory.
|
||||
*
|
||||
* @param jobDir the job directory path
|
||||
*/
|
||||
public StateFiles(Path jobDir) {
|
||||
this.jobDir = Objects.requireNonNull(jobDir, "jobDir must not be null");
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the job directory path.
|
||||
*
|
||||
* @return the job directory path
|
||||
*/
|
||||
public Path getJobDir() {
|
||||
return jobDir;
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// State
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Writes the job state.
|
||||
*
|
||||
* @param state the job state
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeState(JobState state) throws IOException {
|
||||
Objects.requireNonNull(state, "state must not be null");
|
||||
AtomicFiles.writeAtomically(jobDir.resolve(STATE), state.toLowercase());
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the job state.
|
||||
*
|
||||
* @return the job state, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<JobState> readState() throws IOException {
|
||||
return AtomicFiles.readSafely(jobDir.resolve(STATE))
|
||||
.map(JobState::fromString);
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Tag
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Writes the job tag.
|
||||
*
|
||||
* @param tag the tag value
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeTag(String tag) throws IOException {
|
||||
Objects.requireNonNull(tag, "tag must not be null");
|
||||
AtomicFiles.writeAtomically(jobDir.resolve(TAG), tag);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the job tag.
|
||||
*
|
||||
* @return the tag, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<String> readTag() throws IOException {
|
||||
return AtomicFiles.readSafely(jobDir.resolve(TAG));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Timestamps
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Writes the creation timestamp.
|
||||
*
|
||||
* @param timestamp the timestamp
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeCreatedAt(Instant timestamp) throws IOException {
|
||||
writeTimestamp(CREATED_AT, timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the creation timestamp.
|
||||
*
|
||||
* @return the timestamp, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<Instant> readCreatedAt() throws IOException {
|
||||
return readTimestamp(CREATED_AT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the start timestamp.
|
||||
*
|
||||
* @param timestamp the timestamp
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeStartedAt(Instant timestamp) throws IOException {
|
||||
writeTimestamp(STARTED_AT, timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the start timestamp.
|
||||
*
|
||||
* @return the timestamp, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<Instant> readStartedAt() throws IOException {
|
||||
return readTimestamp(STARTED_AT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the finished timestamp.
|
||||
*
|
||||
* @param timestamp the timestamp
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeFinishedAt(Instant timestamp) throws IOException {
|
||||
writeTimestamp(FINISHED_AT, timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the finished timestamp.
|
||||
*
|
||||
* @return the timestamp, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<Instant> readFinishedAt() throws IOException {
|
||||
return readTimestamp(FINISHED_AT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the heartbeat timestamp.
|
||||
*
|
||||
* @param timestamp the timestamp
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeHeartbeat(Instant timestamp) throws IOException {
|
||||
writeTimestamp(HEARTBEAT, timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the heartbeat timestamp.
|
||||
*
|
||||
* @return the timestamp, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<Instant> readHeartbeat() throws IOException {
|
||||
return readTimestamp(HEARTBEAT);
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes the retry timestamp.
|
||||
*
|
||||
* @param timestamp the timestamp
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeRetryAt(Instant timestamp) throws IOException {
|
||||
writeTimestamp(RETRY_AT, timestamp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the retry timestamp.
|
||||
*
|
||||
* @return the timestamp, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<Instant> readRetryAt() throws IOException {
|
||||
return readTimestamp(RETRY_AT);
|
||||
}
|
||||
|
||||
private void writeTimestamp(String filename, Instant timestamp) throws IOException {
|
||||
Objects.requireNonNull(timestamp, "timestamp must not be null");
|
||||
AtomicFiles.writeAtomically(jobDir.resolve(filename), timestamp.toString());
|
||||
}
|
||||
|
||||
private Optional<Instant> readTimestamp(String filename) throws IOException {
|
||||
return AtomicFiles.readSafely(jobDir.resolve(filename))
|
||||
.flatMap(this::parseInstant);
|
||||
}
|
||||
|
||||
private Optional<Instant> parseInstant(String value) {
|
||||
try {
|
||||
return Optional.of(Instant.parse(value));
|
||||
} catch (DateTimeParseException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Exit Code
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Writes the exit code.
|
||||
*
|
||||
* @param code the exit code
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeExitCode(int code) throws IOException {
|
||||
AtomicFiles.writeAtomically(jobDir.resolve(EXIT_CODE), String.valueOf(code));
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a symbolic exit code.
|
||||
*
|
||||
* @param symbolic the symbolic exit code (e.g., "orphaned_process")
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeExitCode(String symbolic) throws IOException {
|
||||
Objects.requireNonNull(symbolic, "symbolic must not be null");
|
||||
AtomicFiles.writeAtomically(jobDir.resolve(EXIT_CODE), symbolic);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the exit code as an integer.
|
||||
*
|
||||
* @return the exit code, or empty if not found or not an integer
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public OptionalInt readExitCode() throws IOException {
|
||||
Optional<String> value = AtomicFiles.readSafely(jobDir.resolve(EXIT_CODE));
|
||||
if (value.isEmpty()) {
|
||||
return OptionalInt.empty();
|
||||
}
|
||||
try {
|
||||
return OptionalInt.of(Integer.parseInt(value.get()));
|
||||
} catch (NumberFormatException e) {
|
||||
return OptionalInt.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the exit code as a string (for symbolic codes).
|
||||
*
|
||||
* @return the exit code string, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<String> readExitCodeString() throws IOException {
|
||||
return AtomicFiles.readSafely(jobDir.resolve(EXIT_CODE));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Error
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Writes the error message.
|
||||
*
|
||||
* @param error the error message
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeError(String error) throws IOException {
|
||||
Objects.requireNonNull(error, "error must not be null");
|
||||
AtomicFiles.writeAtomically(jobDir.resolve(ERROR), error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the error message.
|
||||
*
|
||||
* @return the error message, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<String> readError() throws IOException {
|
||||
return AtomicFiles.readSafely(jobDir.resolve(ERROR));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// PID
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Writes the process ID.
|
||||
*
|
||||
* @param pid the process ID
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writePid(long pid) throws IOException {
|
||||
AtomicFiles.writeAtomically(jobDir.resolve(PID), String.valueOf(pid));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the process ID.
|
||||
*
|
||||
* @return the process ID, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public OptionalLong readPid() throws IOException {
|
||||
Optional<String> value = AtomicFiles.readSafely(jobDir.resolve(PID));
|
||||
if (value.isEmpty()) {
|
||||
return OptionalLong.empty();
|
||||
}
|
||||
try {
|
||||
return OptionalLong.of(Long.parseLong(value.get()));
|
||||
} catch (NumberFormatException e) {
|
||||
return OptionalLong.empty();
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Retry Count
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Writes the retry count.
|
||||
*
|
||||
* @param count the retry count
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeRetryCount(int count) throws IOException {
|
||||
AtomicFiles.writeAtomically(jobDir.resolve(RETRY_COUNT), String.valueOf(count));
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the retry count.
|
||||
*
|
||||
* @return the retry count, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public OptionalInt readRetryCount() throws IOException {
|
||||
Optional<String> value = AtomicFiles.readSafely(jobDir.resolve(RETRY_COUNT));
|
||||
if (value.isEmpty()) {
|
||||
return OptionalInt.empty();
|
||||
}
|
||||
try {
|
||||
return OptionalInt.of(Integer.parseInt(value.get()));
|
||||
} catch (NumberFormatException e) {
|
||||
return OptionalInt.empty();
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Retry History
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Appends an entry to the retry history.
|
||||
*
|
||||
* @param entry the entry to append
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void appendRetryHistory(String entry) throws IOException {
|
||||
Objects.requireNonNull(entry, "entry must not be null");
|
||||
Path historyFile = jobDir.resolve(RETRY_HISTORY);
|
||||
String existing = AtomicFiles.readOrEmpty(historyFile);
|
||||
String newContent = existing.isEmpty() ? entry : existing + "\n" + entry;
|
||||
AtomicFiles.writeAtomically(historyFile, newContent);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the retry history.
|
||||
*
|
||||
* @return the retry history, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<String> readRetryHistory() throws IOException {
|
||||
return AtomicFiles.readSafely(jobDir.resolve(RETRY_HISTORY));
|
||||
}
|
||||
|
||||
// ========================================================================
|
||||
// Stage
|
||||
// ========================================================================
|
||||
|
||||
/**
|
||||
* Writes the current stage.
|
||||
*
|
||||
* @param stage the stage name
|
||||
* @throws IOException if writing fails
|
||||
*/
|
||||
public void writeStage(String stage) throws IOException {
|
||||
Objects.requireNonNull(stage, "stage must not be null");
|
||||
AtomicFiles.writeAtomically(jobDir.resolve(STAGE), stage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the current stage.
|
||||
*
|
||||
* @return the stage, or empty if not found
|
||||
* @throws IOException if reading fails
|
||||
*/
|
||||
public Optional<String> readStage() throws IOException {
|
||||
return AtomicFiles.readSafely(jobDir.resolve(STAGE));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user