Archived
Compare commits
No files matched your search
@@ -0,0 +1,75 @@
|
|||||||
|
---
|
||||||
|
name: git
|
||||||
|
description: How to do git in the barn repo — branches, commits, pushing, pull requests and the Gitea remote. Use whenever committing, branching, pushing, rebasing or opening a PR here.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Git in `barn`
|
||||||
|
|
||||||
|
Remote: `https://gitea.samson.media/samson-media/barn.git` (Gitea, not GitHub). Default branch: `main`.
|
||||||
|
|
||||||
|
## Ground rules
|
||||||
|
|
||||||
|
- Pull requests go through **`tea`** (already logged in as `gitea.samson.media`), not `gh` — `gh` can't resolve these repos. Some older docs still show `gh pr create`; translate it:
|
||||||
|
`tea pulls create --base main --head <branch> --title "..." --description "..."`
|
||||||
|
- PRs are merged in Gitea with **"Create merge commit"**, which produces `Merge pull request '<title>' (#N) from <branch> into <base>`. Don't squash or rebase-merge unless the user asks.
|
||||||
|
- Only commit, push or open a PR when the user asked for it. Approval for one push doesn't cover the next.
|
||||||
|
- Stage specific paths (`git add path/to/file`), never `git add -A` / `git add .` — untracked local dirs such as `.ignore/` (secret mirrors) must never be committed.
|
||||||
|
- Never commit secrets, `.env` files or credentials.
|
||||||
|
- Never `git push --force`, `git reset --hard`, `git clean -f` or delete remote branches without the user typing **CONFIRM DESTRUCTIVE ACTION**. If a push is rejected, fetch and rebase; don't force.
|
||||||
|
- Never `--no-verify` to get past a hook. Fix the cause.
|
||||||
|
- End commit messages with the attribution trailer your harness specifies (e.g. `Co-Authored-By: ...`).
|
||||||
|
|
||||||
|
## Everyday flow
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git status -sb # check branch and ahead/behind first
|
||||||
|
git fetch origin
|
||||||
|
git rebase origin/main # or the branch you're on; rebase unpushed work, don't merge it
|
||||||
|
git add <paths>
|
||||||
|
git commit -m "<message>"
|
||||||
|
git push origin <branch> # use -u the first time for a new branch
|
||||||
|
```
|
||||||
|
|
||||||
|
Diverged from the remote (ahead N, behind M)? `git fetch` then `git rebase origin/<branch>`. Rebasing is fine for commits that are not pushed yet; for pushed commits ask first.
|
||||||
|
|
||||||
|
## Branches
|
||||||
|
|
||||||
|
Default branch `main`. Work on a branch (`feat/...`, `fix/...`, `chore/...`, `docs/...`), PR into `main`, merge with a merge commit. Releases are cut with a `Release vX.Y.Z` commit (see `release.yml`) — never tag or bump versions unless asked.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git checkout main && git pull origin main
|
||||||
|
git checkout -b feat/retry-columns
|
||||||
|
# ...work...
|
||||||
|
mvn verify # must pass before every commit
|
||||||
|
git add <paths>
|
||||||
|
git commit -m "feat(cli): add retry columns to barn status output"
|
||||||
|
git push -u origin feat/retry-columns
|
||||||
|
tea pulls create --base main --head feat/retry-columns --title "feat(cli): ..." --description "..."
|
||||||
|
```
|
||||||
|
|
||||||
|
## Commit messages — Conventional Commits
|
||||||
|
|
||||||
|
`type(scope): description`, lower-case, imperative. Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`, `ci`; breaking changes get `!`. Examples from history:
|
||||||
|
|
||||||
|
```
|
||||||
|
feat(cli): add retry columns to barn status output
|
||||||
|
fix(config): add load section to config show and fix env var override
|
||||||
|
fix(ci): replace HOMEBREW_TAP_TOKEN PAT with GitHub App token
|
||||||
|
chore: bump version to 0.2.0
|
||||||
|
```
|
||||||
|
|
||||||
|
If there is a tracking issue, mention it in the body (`Refs #N`).
|
||||||
|
|
||||||
|
## Pre-commit hook
|
||||||
|
|
||||||
|
`.githooks/pre-commit` runs quality checks on staged `.java` files. Enable it once per clone:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git config core.hooksPath .githooks
|
||||||
|
```
|
||||||
|
|
||||||
|
If it fails, fix the problem and commit again — don't `--no-verify`. See the Commit Checklist in `AGENTS.md`.
|
||||||
|
|
||||||
|
## After pushing
|
||||||
|
|
||||||
|
Update this repo's pointer in the parent `development` repo (see the root git skill).
|
||||||
Symlink
+1
@@ -0,0 +1 @@
|
|||||||
|
../.agents/skills
|
||||||
@@ -128,11 +128,20 @@ jobs:
|
|||||||
echo "linux_arm64_sha=$(grep barn-linux-arm64 SHA256SUMS | awk '{print $1}')" >> $GITHUB_OUTPUT
|
echo "linux_arm64_sha=$(grep barn-linux-arm64 SHA256SUMS | awk '{print $1}')" >> $GITHUB_OUTPUT
|
||||||
echo "linux_x64_sha=$(grep barn-linux-x64 SHA256SUMS | awk '{print $1}')" >> $GITHUB_OUTPUT
|
echo "linux_x64_sha=$(grep barn-linux-x64 SHA256SUMS | awk '{print $1}')" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Generate Homebrew tap token
|
||||||
|
uses: actions/create-github-app-token@v2
|
||||||
|
id: homebrew-token
|
||||||
|
with:
|
||||||
|
app-id: ${{ vars.HOMEBREW_APP_ID }}
|
||||||
|
private-key: ${{ secrets.HOMEBREW_APP_PRIVATE_KEY }}
|
||||||
|
owner: samson-media
|
||||||
|
repositories: homebrew-tap
|
||||||
|
|
||||||
- name: Checkout homebrew tap
|
- name: Checkout homebrew tap
|
||||||
uses: actions/checkout@v4
|
uses: actions/checkout@v4
|
||||||
with:
|
with:
|
||||||
repository: samson-media/homebrew-tap
|
repository: samson-media/homebrew-tap
|
||||||
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
|
token: ${{ steps.homebrew-token.outputs.token }}
|
||||||
path: homebrew-tap
|
path: homebrew-tap
|
||||||
|
|
||||||
- name: Update Homebrew formula
|
- name: Update Homebrew formula
|
||||||
|
|||||||
@@ -0,0 +1,929 @@
|
|||||||
|
# Agent Instructions for Barn
|
||||||
|
|
||||||
|
> **FIRST STEP - MANDATORY**: Before writing ANY code, read these files:
|
||||||
|
> 1. `README.md` - Project overview
|
||||||
|
> 2. `docs/coding-standards.md` - Code style and conventions
|
||||||
|
> 3. `docs/jobs.md` - Filesystem state layout
|
||||||
|
> 4. `docs/config.md` - Configuration options
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ticket Implementation Process (MANDATORY)
|
||||||
|
|
||||||
|
When assigned a GitHub issue/ticket, follow this **exact process**. Do NOT skip steps.
|
||||||
|
|
||||||
|
### Phase 1: READ (Do Not Write Any Code Yet)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ STOP! Read everything before writing a single line of code │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 1.1: Fetch and Read the Ticket**
|
||||||
|
```bash
|
||||||
|
gh issue view <issue-number>
|
||||||
|
```
|
||||||
|
|
||||||
|
Read the ENTIRE ticket including:
|
||||||
|
- Overview and Context
|
||||||
|
- Requirements (every numbered item)
|
||||||
|
- Acceptance Criteria (every checkbox)
|
||||||
|
- Implementation Notes
|
||||||
|
- Tests Required
|
||||||
|
|
||||||
|
**Step 1.2: Check Dependencies**
|
||||||
|
```bash
|
||||||
|
# List dependency issues
|
||||||
|
gh issue view <issue-number> --json body | grep -o '#[0-9]*'
|
||||||
|
|
||||||
|
# Check if dependencies are closed
|
||||||
|
gh issue view <dep-number> --json state
|
||||||
|
```
|
||||||
|
|
||||||
|
If dependencies are NOT closed: **STOP**. Work on dependencies first or inform the user.
|
||||||
|
|
||||||
|
**Step 1.3: Read Referenced Documentation**
|
||||||
|
|
||||||
|
The ticket's "Context" section lists docs to read. Read ALL of them:
|
||||||
|
```bash
|
||||||
|
# Example: if ticket says "Read first: docs/jobs.md"
|
||||||
|
cat docs/jobs.md
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 1.4: Read Related Existing Code**
|
||||||
|
|
||||||
|
If the ticket depends on other issues, read the code they produced:
|
||||||
|
```bash
|
||||||
|
# Find relevant files
|
||||||
|
find src -name "*.java" | xargs grep -l "RelatedClass"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 2: PLAN (Still No Implementation Code)
|
||||||
|
|
||||||
|
**Step 2.1: List All Deliverables**
|
||||||
|
|
||||||
|
Extract from the ticket:
|
||||||
|
- [ ] Classes/files to create
|
||||||
|
- [ ] Methods to implement
|
||||||
|
- [ ] Tests to write
|
||||||
|
- [ ] Acceptance criteria to satisfy
|
||||||
|
|
||||||
|
**Step 2.2: Identify Test Cases**
|
||||||
|
|
||||||
|
From the "Tests Required" section, list every test:
|
||||||
|
```
|
||||||
|
Example:
|
||||||
|
- JobManagerTest.java
|
||||||
|
- createJob_withValidCommand_shouldReturnJobWithUniqueId
|
||||||
|
- createJob_withNullCommand_shouldThrowNullPointerException
|
||||||
|
- findJob_withExistingId_shouldReturnJob
|
||||||
|
- findJob_withMissingId_shouldReturnEmpty
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 3: TEST (Write Tests FIRST)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────┐
|
||||||
|
│ Write ALL tests before writing ANY implementation code │
|
||||||
|
└─────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 3.1: Create Test File**
|
||||||
|
```java
|
||||||
|
// src/test/java/com/samsonmedia/barn/<package>/<Class>Test.java
|
||||||
|
class JobManagerTest {
|
||||||
|
@Test
|
||||||
|
void methodName_condition_expectedResult() {
|
||||||
|
// Arrange
|
||||||
|
// Act
|
||||||
|
// Assert - use AssertJ
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 3.2: Write ALL Test Cases**
|
||||||
|
|
||||||
|
Write tests for:
|
||||||
|
1. Happy path (normal success)
|
||||||
|
2. Edge cases (empty, boundary values)
|
||||||
|
3. Error cases (null, invalid state)
|
||||||
|
4. Every acceptance criterion
|
||||||
|
|
||||||
|
**Step 3.3: Run Tests (Must FAIL)**
|
||||||
|
```bash
|
||||||
|
mvn test -Dtest=<TestClass>
|
||||||
|
# Expected: FAILURE (code not implemented yet)
|
||||||
|
```
|
||||||
|
|
||||||
|
If tests pass before implementation, the tests are wrong.
|
||||||
|
|
||||||
|
### Phase 4: IMPLEMENT (Now Write Code)
|
||||||
|
|
||||||
|
**Step 4.1: Implement Minimum Code**
|
||||||
|
|
||||||
|
Write the minimum code to make ONE test pass at a time:
|
||||||
|
```bash
|
||||||
|
# After each small change
|
||||||
|
mvn test -Dtest=<TestClass>#<testMethod>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 4.2: Follow Coding Standards**
|
||||||
|
|
||||||
|
Every file must:
|
||||||
|
- Have no wildcard imports
|
||||||
|
- Use `Optional<T>` not null returns
|
||||||
|
- Use `Objects.requireNonNull()` for parameters
|
||||||
|
- Use `final` for immutable fields
|
||||||
|
- Have proper Javadoc on public methods
|
||||||
|
|
||||||
|
**Step 4.3: Iterate Until All Tests Pass**
|
||||||
|
```bash
|
||||||
|
mvn test -Dtest=<TestClass>
|
||||||
|
# Expected: SUCCESS for all tests
|
||||||
|
```
|
||||||
|
|
||||||
|
### Phase 5: VERIFY (Full Quality Check)
|
||||||
|
|
||||||
|
**Step 5.1: Run Full Verification**
|
||||||
|
```bash
|
||||||
|
mvn verify
|
||||||
|
```
|
||||||
|
|
||||||
|
This MUST pass:
|
||||||
|
- ✓ Checkstyle (formatting)
|
||||||
|
- ✓ Compilation (no warnings)
|
||||||
|
- ✓ All unit tests
|
||||||
|
- ✓ SpotBugs (no bugs)
|
||||||
|
- ✓ PMD (no violations)
|
||||||
|
- ✓ JaCoCo (80%+ coverage)
|
||||||
|
|
||||||
|
**Step 5.2: Check Acceptance Criteria**
|
||||||
|
|
||||||
|
Go through EVERY checkbox in the ticket:
|
||||||
|
```
|
||||||
|
- [ ] Criterion 1 → Verify manually or with test
|
||||||
|
- [ ] Criterion 2 → Verify manually or with test
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 5.3: Fix Any Issues**
|
||||||
|
|
||||||
|
If `mvn verify` fails:
|
||||||
|
1. Read the error message
|
||||||
|
2. Fix the issue
|
||||||
|
3. Run `mvn verify` again
|
||||||
|
4. Repeat until clean
|
||||||
|
|
||||||
|
### Phase 6: COMPLETE (Commit and Close)
|
||||||
|
|
||||||
|
**Step 6.1: Commit with Conventional Message**
|
||||||
|
```bash
|
||||||
|
git add .
|
||||||
|
git commit -m "feat(<scope>): <description>
|
||||||
|
|
||||||
|
Implements #<issue-number>
|
||||||
|
|
||||||
|
- Added <component>
|
||||||
|
- Implemented <feature>
|
||||||
|
- Tests for <functionality>
|
||||||
|
|
||||||
|
Co-Authored-By: <your agent's attribution line, if any>"
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 6.2: Verify Commit**
|
||||||
|
```bash
|
||||||
|
# Ensure nothing is missed
|
||||||
|
git status
|
||||||
|
mvn verify # Run one final time
|
||||||
|
```
|
||||||
|
|
||||||
|
**Step 6.3: Close the Ticket**
|
||||||
|
```bash
|
||||||
|
gh issue close <issue-number> --comment "Implemented in commit <sha>"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ticket Process Checklist
|
||||||
|
|
||||||
|
Copy this checklist for each ticket:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Ticket #XX: <Title>
|
||||||
|
|
||||||
|
### Phase 1: READ
|
||||||
|
- [ ] Fetched ticket with `gh issue view`
|
||||||
|
- [ ] Read entire ticket description
|
||||||
|
- [ ] Checked all dependencies are closed
|
||||||
|
- [ ] Read all referenced documentation
|
||||||
|
- [ ] Read related existing code
|
||||||
|
|
||||||
|
### Phase 2: PLAN
|
||||||
|
- [ ] Listed all classes/files to create
|
||||||
|
- [ ] Listed all methods to implement
|
||||||
|
- [ ] Listed all test cases from ticket
|
||||||
|
|
||||||
|
### Phase 3: TEST
|
||||||
|
- [ ] Created test file(s)
|
||||||
|
- [ ] Wrote all test cases
|
||||||
|
- [ ] Tests fail (code not implemented)
|
||||||
|
|
||||||
|
### Phase 4: IMPLEMENT
|
||||||
|
- [ ] Implemented code to pass tests
|
||||||
|
- [ ] All tests pass
|
||||||
|
- [ ] Followed coding standards
|
||||||
|
|
||||||
|
### Phase 5: VERIFY
|
||||||
|
- [ ] `mvn verify` passes
|
||||||
|
- [ ] All acceptance criteria checked
|
||||||
|
- [ ] No TODO/FIXME without issue
|
||||||
|
|
||||||
|
### Phase 6: COMPLETE
|
||||||
|
- [ ] Committed with conventional message
|
||||||
|
- [ ] Closed ticket with `gh issue close`
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Critical Requirements
|
||||||
|
|
||||||
|
### 1. ALWAYS Write Tests First
|
||||||
|
|
||||||
|
**Every code change MUST include automated tests.** No exceptions.
|
||||||
|
|
||||||
|
```
|
||||||
|
Code without tests = Incomplete work
|
||||||
|
```
|
||||||
|
|
||||||
|
Before implementing any feature or fix:
|
||||||
|
1. Write failing tests that define the expected behavior
|
||||||
|
2. Implement the code to make tests pass
|
||||||
|
3. Run `mvn verify` to ensure all checks pass
|
||||||
|
4. Only then consider the work complete
|
||||||
|
|
||||||
|
### 2. ALWAYS Validate with Tests
|
||||||
|
|
||||||
|
After writing code, ALWAYS run:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mvn verify
|
||||||
|
```
|
||||||
|
|
||||||
|
This runs:
|
||||||
|
- Compilation with `-Werror` (warnings are errors)
|
||||||
|
- Checkstyle (code formatting)
|
||||||
|
- Unit tests
|
||||||
|
- SpotBugs (bug detection)
|
||||||
|
- PMD (static analysis)
|
||||||
|
- JaCoCo (coverage check - must be 80%+)
|
||||||
|
|
||||||
|
**Do NOT consider code complete until `mvn verify` passes.**
|
||||||
|
|
||||||
|
### 3. ALWAYS Follow Coding Standards
|
||||||
|
|
||||||
|
Read `docs/coding-standards.md` before writing code. Key rules:
|
||||||
|
- 4 spaces indentation, 120 char line limit
|
||||||
|
- No wildcard imports
|
||||||
|
- Use `Optional<T>` instead of returning `null`
|
||||||
|
- Use `Objects.requireNonNull()` for constructor params
|
||||||
|
- Use `final` for fields that don't change
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Project Overview
|
||||||
|
|
||||||
|
Barn is a cross-platform job daemon for managing long-running media processing tasks (FFmpeg, WebDAV transfers). It runs as an OS service on Windows, macOS, and Linux.
|
||||||
|
|
||||||
|
## Technology Stack
|
||||||
|
|
||||||
|
- **Language**: Java 21+
|
||||||
|
- **Build**: Maven
|
||||||
|
- **Native Image**: GraalVM Native Image
|
||||||
|
- **Code Style**: Checkstyle (Google Java Style)
|
||||||
|
- **Static Analysis**: SpotBugs, PMD
|
||||||
|
- **Testing**: JUnit 5, Mockito, AssertJ
|
||||||
|
- **Coverage**: JaCoCo (80% minimum)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Testing Requirements (MANDATORY)
|
||||||
|
|
||||||
|
### Test Coverage Requirements
|
||||||
|
|
||||||
|
| Type | Minimum | Target |
|
||||||
|
|------|---------|--------|
|
||||||
|
| Line coverage | 80% | 90%+ |
|
||||||
|
| Branch coverage | 70% | 80%+ |
|
||||||
|
| New code | 100% | 100% |
|
||||||
|
|
||||||
|
### Test Naming Convention
|
||||||
|
|
||||||
|
```java
|
||||||
|
// Pattern: methodName_condition_expectedResult
|
||||||
|
@Test
|
||||||
|
void createJob_withValidCommand_shouldReturnJobWithUniqueId() { }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void createJob_withNullCommand_shouldThrowNullPointerException() { }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void processJob_whenServiceNotRunning_shouldThrowIllegalStateException() { }
|
||||||
|
```
|
||||||
|
|
||||||
|
### Test Structure (AAA Pattern)
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Test
|
||||||
|
void findJob_withExistingId_shouldReturnJob() {
|
||||||
|
// Arrange
|
||||||
|
var manager = new JobManager(testConfig);
|
||||||
|
var job = manager.createJob(new Command("echo", "test"));
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = manager.findJob(job.getId());
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertThat(result).isPresent();
|
||||||
|
assertThat(result.get().getId()).isEqualTo(job.getId());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### What to Test
|
||||||
|
|
||||||
|
For EVERY class you create or modify:
|
||||||
|
|
||||||
|
1. **Happy path** - Normal successful operation
|
||||||
|
2. **Edge cases** - Empty inputs, boundary values
|
||||||
|
3. **Error cases** - Null inputs, invalid states
|
||||||
|
4. **Integration** - Component interactions
|
||||||
|
|
||||||
|
### Test File Location
|
||||||
|
|
||||||
|
```
|
||||||
|
src/
|
||||||
|
main/java/com/samsonmedia/barn/
|
||||||
|
jobs/
|
||||||
|
JobManager.java
|
||||||
|
test/java/com/samsonmedia/barn/
|
||||||
|
jobs/
|
||||||
|
JobManagerTest.java # Unit tests
|
||||||
|
JobManagerIT.java # Integration tests
|
||||||
|
```
|
||||||
|
|
||||||
|
### Running Tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run all tests
|
||||||
|
mvn test
|
||||||
|
|
||||||
|
# Run specific test class
|
||||||
|
mvn test -Dtest=JobManagerTest
|
||||||
|
|
||||||
|
# Run with coverage report
|
||||||
|
mvn test jacoco:report
|
||||||
|
# View: target/site/jacoco/index.html
|
||||||
|
|
||||||
|
# Run full verification (ALWAYS do this before committing)
|
||||||
|
mvn verify
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Workflow for Every Code Change
|
||||||
|
|
||||||
|
### Step 1: Understand the Requirement
|
||||||
|
- Read relevant docs
|
||||||
|
- Understand existing code patterns
|
||||||
|
|
||||||
|
### Step 2: Write Tests FIRST
|
||||||
|
```java
|
||||||
|
// Write test that defines expected behavior
|
||||||
|
@Test
|
||||||
|
void newFeature_shouldDoExpectedThing() {
|
||||||
|
// Arrange
|
||||||
|
var component = new Component();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
var result = component.newFeature();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertThat(result).isEqualTo(expected);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 3: Run Tests (Should Fail)
|
||||||
|
```bash
|
||||||
|
mvn test -Dtest=ComponentTest#newFeature_shouldDoExpectedThing
|
||||||
|
# Expected: FAILURE (test written, code not yet implemented)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 4: Implement the Code
|
||||||
|
Write minimal code to make the test pass.
|
||||||
|
|
||||||
|
### Step 5: Run Tests (Should Pass)
|
||||||
|
```bash
|
||||||
|
mvn test -Dtest=ComponentTest#newFeature_shouldDoExpectedThing
|
||||||
|
# Expected: SUCCESS
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 6: Run Full Verification
|
||||||
|
```bash
|
||||||
|
mvn verify
|
||||||
|
# Must pass ALL checks:
|
||||||
|
# - Checkstyle
|
||||||
|
# - Compilation
|
||||||
|
# - All tests
|
||||||
|
# - SpotBugs
|
||||||
|
# - PMD
|
||||||
|
# - Coverage thresholds
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 7: Only THEN Consider Complete
|
||||||
|
If `mvn verify` fails, fix the issues and repeat.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Code Standards Summary
|
||||||
|
|
||||||
|
### Formatting
|
||||||
|
- 4 spaces indentation (no tabs)
|
||||||
|
- 120 character line limit
|
||||||
|
- K&R brace style (opening brace on same line)
|
||||||
|
- Static imports first, then regular imports, alphabetically
|
||||||
|
|
||||||
|
### Naming
|
||||||
|
- Packages: `lowercase`
|
||||||
|
- Classes/Interfaces: `PascalCase`
|
||||||
|
- Methods/Variables: `camelCase`
|
||||||
|
- Constants: `SCREAMING_SNAKE_CASE`
|
||||||
|
|
||||||
|
### Java Idioms
|
||||||
|
```java
|
||||||
|
// Use final for immutable fields
|
||||||
|
private final Config config;
|
||||||
|
|
||||||
|
// Use Optional for nullable returns
|
||||||
|
public Optional<Job> findJob(String id) {
|
||||||
|
return Optional.ofNullable(jobs.get(id));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate constructor params
|
||||||
|
public JobManager(Config config) {
|
||||||
|
this.config = Objects.requireNonNull(config, "config must not be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use records for value objects
|
||||||
|
public record Job(String id, JobState state, Instant createdAt) {}
|
||||||
|
|
||||||
|
// Use switch expressions
|
||||||
|
String status = switch (state) {
|
||||||
|
case QUEUED -> "Waiting";
|
||||||
|
case RUNNING -> "Executing";
|
||||||
|
case FAILED -> "Failed";
|
||||||
|
case SUCCEEDED -> "Done";
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
### Error Handling
|
||||||
|
```java
|
||||||
|
// Use Optional, not null
|
||||||
|
public Optional<Job> findJob(String id);
|
||||||
|
|
||||||
|
// Validate preconditions
|
||||||
|
public void processJob(Job job) {
|
||||||
|
Objects.requireNonNull(job, "job");
|
||||||
|
if (job.getState() != JobState.QUEUED) {
|
||||||
|
throw new IllegalStateException("Job must be QUEUED");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create domain exceptions
|
||||||
|
public class JobNotFoundException extends RuntimeException {
|
||||||
|
public JobNotFoundException(String jobId) {
|
||||||
|
super("Job not found: " + jobId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Architecture Principles
|
||||||
|
|
||||||
|
### Filesystem as Database
|
||||||
|
- Job state stored in `/tmp/barn/jobs/<job-id>/`
|
||||||
|
- Use atomic file operations
|
||||||
|
- Human-readable plain text files
|
||||||
|
- No external database dependencies
|
||||||
|
|
||||||
|
### Cross-Platform
|
||||||
|
- Use `System.getProperty("java.io.tmpdir")` for temp paths
|
||||||
|
- Avoid platform-specific commands
|
||||||
|
- Test on Windows, macOS, and Linux
|
||||||
|
|
||||||
|
### GraalVM Native Image
|
||||||
|
- Avoid reflection where possible
|
||||||
|
- Register any reflection in `reflect-config.json`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## File Structure
|
||||||
|
|
||||||
|
```
|
||||||
|
barn/
|
||||||
|
src/
|
||||||
|
main/java/com/samsonmedia/barn/
|
||||||
|
Main.java # Entry point
|
||||||
|
cli/ # CLI commands (picocli)
|
||||||
|
config/ # Configuration parsing
|
||||||
|
jobs/ # Job management
|
||||||
|
service/ # Daemon/service logic
|
||||||
|
state/ # Filesystem state management
|
||||||
|
test/java/com/samsonmedia/barn/
|
||||||
|
# Mirror structure with Test suffix
|
||||||
|
config/
|
||||||
|
checkstyle/ # Checkstyle rules
|
||||||
|
spotbugs/ # SpotBugs exclusions
|
||||||
|
pmd/ # PMD ruleset
|
||||||
|
docs/ # Documentation
|
||||||
|
pom.xml # Maven build
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Commit Checklist
|
||||||
|
|
||||||
|
Before EVERY commit:
|
||||||
|
|
||||||
|
- [ ] Tests written for new/changed code
|
||||||
|
- [ ] `mvn verify` passes
|
||||||
|
- [ ] No `TODO` or `FIXME` without tracking issue
|
||||||
|
- [ ] Javadoc for public API
|
||||||
|
- [ ] Commit message follows Conventional Commits format
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Commit message format
|
||||||
|
feat(jobs): add retry mechanism for failed jobs
|
||||||
|
fix(cli): handle spaces in file paths
|
||||||
|
test(jobs): add integration tests for job lifecycle
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## What NOT to Do
|
||||||
|
|
||||||
|
- **Don't skip tests** - Every change needs tests
|
||||||
|
- **Don't commit without `mvn verify`** - Ensures all checks pass
|
||||||
|
- **Don't return `null`** - Use `Optional<T>` instead
|
||||||
|
- **Don't catch `Exception`** - Catch specific exceptions
|
||||||
|
- **Don't use `System.out.println`** - Use SLF4J logging
|
||||||
|
- **Don't use wildcard imports** - Import specific classes
|
||||||
|
- **Don't use raw types** - Always specify generics
|
||||||
|
- **Don't ignore warnings** - Fix them (they're errors with `-Werror`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Reference
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Build
|
||||||
|
mvn package
|
||||||
|
|
||||||
|
# Test
|
||||||
|
mvn test
|
||||||
|
|
||||||
|
# Full verification (ALWAYS before commit)
|
||||||
|
mvn verify
|
||||||
|
|
||||||
|
# Coverage report
|
||||||
|
mvn test jacoco:report
|
||||||
|
|
||||||
|
# Fast build (skip checks - use sparingly)
|
||||||
|
mvn package -Pfast
|
||||||
|
|
||||||
|
# Specific test
|
||||||
|
mvn test -Dtest=JobManagerTest
|
||||||
|
|
||||||
|
# View SpotBugs in GUI
|
||||||
|
mvn compile spotbugs:gui
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Pre-Release Testing Checklist (MANDATORY)
|
||||||
|
|
||||||
|
Before creating ANY release tag, you MUST test ALL subcommands with the native binary locally.
|
||||||
|
|
||||||
|
### Prerequisites
|
||||||
|
|
||||||
|
1. **Build the native image locally:**
|
||||||
|
```bash
|
||||||
|
export JAVA_HOME="/Library/Java/JavaVirtualMachines/graalvm-25.jdk/Contents/Home"
|
||||||
|
mvn package -Pnative -DskipTests -Dspotbugs.skip=true -Dpmd.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Verify the binary exists:**
|
||||||
|
```bash
|
||||||
|
ls -la target/barn
|
||||||
|
```
|
||||||
|
|
||||||
|
### Test Every Subcommand
|
||||||
|
|
||||||
|
Run each command and verify the expected output. **Do NOT skip any command.**
|
||||||
|
|
||||||
|
#### Basic Commands
|
||||||
|
```bash
|
||||||
|
# Should show usage/help
|
||||||
|
./target/barn
|
||||||
|
# Expected: Shows "Usage: barn [-hV] [COMMAND]" and lists all subcommands
|
||||||
|
|
||||||
|
./target/barn --help
|
||||||
|
# Expected: Same as above
|
||||||
|
|
||||||
|
./target/barn --version
|
||||||
|
# Expected: Shows "barn X.Y.Z"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Service Commands (Start service first)
|
||||||
|
```bash
|
||||||
|
# Stop any existing service
|
||||||
|
./target/barn service stop 2>/dev/null || true
|
||||||
|
|
||||||
|
# Start the service
|
||||||
|
./target/barn service start
|
||||||
|
# Expected: "Barn service started (PID: XXXXX)"
|
||||||
|
|
||||||
|
# Check service status
|
||||||
|
./target/barn service status
|
||||||
|
# Expected: Shows "Status: running", PID, uptime, job counts
|
||||||
|
|
||||||
|
# Test reload (reloads config without restart)
|
||||||
|
./target/barn service reload
|
||||||
|
# Expected: "Configuration reloaded"
|
||||||
|
|
||||||
|
# View logs
|
||||||
|
./target/barn service logs
|
||||||
|
# Expected: Shows recent log entries or "No logs found"
|
||||||
|
|
||||||
|
# Restart the service
|
||||||
|
./target/barn service restart
|
||||||
|
# Expected: "Barn service restarted"
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Job Commands (Service must be running)
|
||||||
|
```bash
|
||||||
|
# Run a test job
|
||||||
|
./target/barn run -- echo "test from native binary"
|
||||||
|
# Expected: "Job created: job-XXXXXXXX" with state: queued
|
||||||
|
|
||||||
|
# Wait a moment, then check status
|
||||||
|
sleep 2
|
||||||
|
./target/barn status
|
||||||
|
# Expected: Shows table with jobs, including the new job as "succeeded"
|
||||||
|
|
||||||
|
# Get the job ID from status output, then describe it
|
||||||
|
./target/barn describe <job-id>
|
||||||
|
# Expected: Shows detailed job info including timestamps, exit code, files
|
||||||
|
|
||||||
|
# Check resource usage
|
||||||
|
./target/barn usage <job-id>
|
||||||
|
# Expected: Shows CPU/memory/disk usage samples
|
||||||
|
|
||||||
|
# Test kill on a non-running job (should fail gracefully)
|
||||||
|
./target/barn kill <job-id>
|
||||||
|
# Expected: "Error: Job is not running: SUCCEEDED"
|
||||||
|
|
||||||
|
# Clean with dry-run
|
||||||
|
./target/barn clean --dry-run
|
||||||
|
# Expected: "Would clean X jobs:" followed by list
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Config Commands
|
||||||
|
```bash
|
||||||
|
./target/barn config show
|
||||||
|
# Expected: Shows configuration with all sections (service, jobs, cleanup, storage)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Autocompletion Commands
|
||||||
|
```bash
|
||||||
|
./target/barn autocompletion --bash | head -5
|
||||||
|
# Expected: Shows bash completion script starting with "#!/usr/bin/env bash"
|
||||||
|
|
||||||
|
./target/barn autocompletion --zsh | head -5
|
||||||
|
# Expected: Shows zsh completion script
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Service Stop (Clean up)
|
||||||
|
```bash
|
||||||
|
./target/barn service stop
|
||||||
|
# Expected: "Barn service stopped"
|
||||||
|
|
||||||
|
./target/barn service status
|
||||||
|
# Expected: "Barn service is not running"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Checklist Summary
|
||||||
|
|
||||||
|
Copy this checklist and verify each item:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Pre-Release Testing for vX.Y.Z
|
||||||
|
|
||||||
|
### Build
|
||||||
|
- [ ] Native image builds successfully
|
||||||
|
- [ ] Binary exists at target/barn
|
||||||
|
|
||||||
|
### Basic Commands
|
||||||
|
- [ ] `barn` shows help
|
||||||
|
- [ ] `barn --help` shows help
|
||||||
|
- [ ] `barn --version` shows correct version
|
||||||
|
|
||||||
|
### Service Commands
|
||||||
|
- [ ] `barn service start` starts the service
|
||||||
|
- [ ] `barn service status` shows running status
|
||||||
|
- [ ] `barn service reload` reloads config
|
||||||
|
- [ ] `barn service logs` shows logs
|
||||||
|
- [ ] `barn service restart` restarts cleanly
|
||||||
|
- [ ] `barn service stop` stops the service
|
||||||
|
|
||||||
|
### Job Commands (with service running)
|
||||||
|
- [ ] `barn run -- echo test` creates a job
|
||||||
|
- [ ] `barn status` shows job list
|
||||||
|
- [ ] `barn describe <id>` shows job details
|
||||||
|
- [ ] `barn usage <id>` shows resource usage
|
||||||
|
- [ ] `barn kill <id>` handles non-running job gracefully
|
||||||
|
- [ ] `barn clean --dry-run` shows what would be cleaned
|
||||||
|
|
||||||
|
### Config Commands
|
||||||
|
- [ ] `barn config show` displays configuration
|
||||||
|
|
||||||
|
### Autocompletion
|
||||||
|
- [ ] `barn autocompletion --bash` generates bash script
|
||||||
|
- [ ] `barn autocompletion --zsh` generates zsh script
|
||||||
|
|
||||||
|
### Final
|
||||||
|
- [ ] All commands return expected output
|
||||||
|
- [ ] No crashes or exceptions
|
||||||
|
- [ ] Service starts and stops cleanly
|
||||||
|
```
|
||||||
|
|
||||||
|
### Only After All Tests Pass
|
||||||
|
|
||||||
|
1. Commit any fixes
|
||||||
|
2. Push to main
|
||||||
|
3. Wait for CI to pass
|
||||||
|
4. Create the release tag: `git tag vX.Y.Z && git push origin vX.Y.Z`
|
||||||
|
|
||||||
|
**NEVER create a release tag without completing this checklist.**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Questions to Ask Before Implementing
|
||||||
|
|
||||||
|
1. Have I read the relevant documentation?
|
||||||
|
2. Have I written tests that define the expected behavior?
|
||||||
|
3. Does this work on Windows, macOS, AND Linux?
|
||||||
|
4. Will this survive a crash/restart?
|
||||||
|
5. Can the state be manually inspected in the filesystem?
|
||||||
|
6. Does `mvn verify` pass?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Working with GitHub Issues
|
||||||
|
|
||||||
|
### Viewing the Backlog
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# List all open issues
|
||||||
|
gh issue list
|
||||||
|
|
||||||
|
# List issues by milestone
|
||||||
|
gh issue list --milestone "M1: Foundation"
|
||||||
|
|
||||||
|
# List issues by label
|
||||||
|
gh issue list --label "foundation"
|
||||||
|
|
||||||
|
# View specific issue
|
||||||
|
gh issue view 1
|
||||||
|
```
|
||||||
|
|
||||||
|
### Dependency Graph
|
||||||
|
|
||||||
|
Issues must be completed in dependency order. The milestones define the general order:
|
||||||
|
|
||||||
|
```
|
||||||
|
M1: Foundation (#1, #2, #3, #4, #22)
|
||||||
|
↓
|
||||||
|
M2: Job Execution (#5, #6, #7, #20)
|
||||||
|
↓
|
||||||
|
M3: CLI Commands (#8, #9, #10, #11, #12, #13, #21)
|
||||||
|
↓
|
||||||
|
M4: Service Infrastructure (#14, #15, #16)
|
||||||
|
↓
|
||||||
|
M5: Platform Integration (#17, #18, #19)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Recommended order within M1:**
|
||||||
|
```
|
||||||
|
#1 (project structure)
|
||||||
|
→ #22 (logging)
|
||||||
|
→ #2 (configuration)
|
||||||
|
→ #3 (filesystem state)
|
||||||
|
→ #4 (job model)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Starting a New Ticket
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. Check what's ready to work on (no open dependencies)
|
||||||
|
gh issue list --milestone "M1: Foundation" --state open
|
||||||
|
|
||||||
|
# 2. Pick the next ticket with closed dependencies
|
||||||
|
gh issue view 1
|
||||||
|
|
||||||
|
# 3. Follow the Ticket Implementation Process above
|
||||||
|
```
|
||||||
|
|
||||||
|
### Progress Tracking
|
||||||
|
|
||||||
|
After completing a ticket:
|
||||||
|
```bash
|
||||||
|
# Close with comment
|
||||||
|
gh issue close <number> --comment "Implemented in commit abc123"
|
||||||
|
|
||||||
|
# Verify milestone progress
|
||||||
|
gh issue list --milestone "M1: Foundation"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Emergency Procedures
|
||||||
|
|
||||||
|
### If `mvn verify` Fails
|
||||||
|
|
||||||
|
1. **Read the error** - Don't guess, read the actual message
|
||||||
|
2. **Identify the phase** - Checkstyle? Compile? Test? SpotBugs? PMD? JaCoCo?
|
||||||
|
3. **Fix incrementally** - Run just that check until it passes:
|
||||||
|
```bash
|
||||||
|
mvn checkstyle:check # Formatting issues
|
||||||
|
mvn compile # Compilation errors
|
||||||
|
mvn test # Test failures
|
||||||
|
mvn spotbugs:check # Bug detection
|
||||||
|
mvn pmd:check # Static analysis
|
||||||
|
mvn jacoco:check # Coverage issues
|
||||||
|
```
|
||||||
|
4. **Run full verify again** - `mvn verify`
|
||||||
|
|
||||||
|
### If Tests Won't Pass
|
||||||
|
|
||||||
|
1. **Check the test is correct** - Is the expected behavior right?
|
||||||
|
2. **Check dependencies** - Is required code from other tickets present?
|
||||||
|
3. **Check test isolation** - Does the test depend on external state?
|
||||||
|
4. **Run single test** - `mvn test -Dtest=ClassName#methodName`
|
||||||
|
|
||||||
|
### If Stuck on a Ticket
|
||||||
|
|
||||||
|
1. **Re-read the ticket** - Often the answer is in the description
|
||||||
|
2. **Check Implementation Notes** - Specific guidance is provided
|
||||||
|
3. **Check referenced docs** - Context section lists what to read
|
||||||
|
4. **Look at similar code** - How did other tickets solve similar problems?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Ticket Template Reference
|
||||||
|
|
||||||
|
Every ticket follows this structure:
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Overview
|
||||||
|
Brief description of what to implement.
|
||||||
|
|
||||||
|
## Context
|
||||||
|
- **Read first**: docs to read before starting
|
||||||
|
- **Depends on**: prerequisite tickets
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
### 1. Component Name
|
||||||
|
Detailed requirements with code examples.
|
||||||
|
|
||||||
|
### 2. Another Component
|
||||||
|
More requirements...
|
||||||
|
|
||||||
|
## Tests Required
|
||||||
|
- TestClass1.java: description
|
||||||
|
- TestClass2.java: description
|
||||||
|
|
||||||
|
## Acceptance Criteria
|
||||||
|
- [ ] Criterion 1
|
||||||
|
- [ ] Criterion 2
|
||||||
|
- [ ] `mvn verify` passes
|
||||||
|
- [ ] Tests have 80%+ coverage
|
||||||
|
|
||||||
|
## Implementation Notes
|
||||||
|
Specific guidance, code patterns, edge cases.
|
||||||
|
|
||||||
|
## Definition of Done
|
||||||
|
Summary of completion requirements.
|
||||||
|
```
|
||||||
|
|
||||||
|
Use this structure to know exactly what's expected.
|
||||||
+22
-1
@@ -5,13 +5,31 @@ All notable changes to this project will be documented in this file.
|
|||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/).
|
and this project adheres to [Semantic Versioning](https://semver.org/).
|
||||||
|
|
||||||
## [0.1.5] - 2026-01-22
|
## [0.3.0] - 2026-03-03
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- RETRIES and NEXT RETRY columns in `barn status` human table output
|
||||||
|
- Retry At field in single job detail view (`barn describe`)
|
||||||
|
- Retry display tests for human, JSON, and XML output formats
|
||||||
|
|
||||||
|
## [0.1.7] - 2026-01-22
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Native image IPC deserialization (IpcMessage reflection config)
|
||||||
|
|
||||||
|
## [0.1.6] - 2026-01-22
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
- Intel Mac (x86_64) support
|
- Intel Mac (x86_64) support
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
- Homebrew tap now auto-updates on release
|
- Homebrew tap now auto-updates on release
|
||||||
|
- Version string now matches release tag
|
||||||
|
|
||||||
|
## [0.1.5] - 2026-01-22
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Version string was hardcoded (broken release)
|
||||||
|
|
||||||
## [0.1.4] - 2026-01-22
|
## [0.1.4] - 2026-01-22
|
||||||
|
|
||||||
@@ -56,6 +74,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
|
|||||||
- Jobs that fail to start now properly transition to FAILED state
|
- Jobs that fail to start now properly transition to FAILED state
|
||||||
- Startup errors are written to stderr.log for visibility
|
- Startup errors are written to stderr.log for visibility
|
||||||
|
|
||||||
|
[0.3.0]: https://github.com/samson-media/barn/releases/tag/v0.3.0
|
||||||
|
[0.1.7]: https://github.com/samson-media/barn/releases/tag/v0.1.7
|
||||||
|
[0.1.6]: https://github.com/samson-media/barn/releases/tag/v0.1.6
|
||||||
[0.1.5]: https://github.com/samson-media/barn/releases/tag/v0.1.5
|
[0.1.5]: https://github.com/samson-media/barn/releases/tag/v0.1.5
|
||||||
[0.1.4]: https://github.com/samson-media/barn/releases/tag/v0.1.4
|
[0.1.4]: https://github.com/samson-media/barn/releases/tag/v0.1.4
|
||||||
[0.1.3]: https://github.com/samson-media/barn/releases/tag/v0.1.3
|
[0.1.3]: https://github.com/samson-media/barn/releases/tag/v0.1.3
|
||||||
|
|||||||
@@ -1,929 +1,7 @@
|
|||||||
# Claude AI Instructions for Barn
|
# CLAUDE.md
|
||||||
|
|
||||||
> **FIRST STEP - MANDATORY**: Before writing ANY code, read these files:
|
Agent instructions for this repository live in [AGENTS.md](AGENTS.md) so they are
|
||||||
> 1. `README.md` - Project overview
|
shared across coding agents (Claude Code, Codex, Gemini CLI, Cursor, etc.).
|
||||||
> 2. `docs/coding-standards.md` - Code style and conventions
|
Claude Code loads them via the import below; add Claude-only notes underneath.
|
||||||
> 3. `docs/jobs.md` - Filesystem state layout
|
|
||||||
> 4. `docs/config.md` - Configuration options
|
|
||||||
|
|
||||||
---
|
@AGENTS.md
|
||||||
|
|
||||||
## Ticket Implementation Process (MANDATORY)
|
|
||||||
|
|
||||||
When assigned a GitHub issue/ticket, follow this **exact process**. Do NOT skip steps.
|
|
||||||
|
|
||||||
### Phase 1: READ (Do Not Write Any Code Yet)
|
|
||||||
|
|
||||||
```
|
|
||||||
┌─────────────────────────────────────────────────────────────┐
|
|
||||||
│ STOP! Read everything before writing a single line of code │
|
|
||||||
└─────────────────────────────────────────────────────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
**Step 1.1: Fetch and Read the Ticket**
|
|
||||||
```bash
|
|
||||||
gh issue view <issue-number>
|
|
||||||
```
|
|
||||||
|
|
||||||
Read the ENTIRE ticket including:
|
|
||||||
- Overview and Context
|
|
||||||
- Requirements (every numbered item)
|
|
||||||
- Acceptance Criteria (every checkbox)
|
|
||||||
- Implementation Notes
|
|
||||||
- Tests Required
|
|
||||||
|
|
||||||
**Step 1.2: Check Dependencies**
|
|
||||||
```bash
|
|
||||||
# List dependency issues
|
|
||||||
gh issue view <issue-number> --json body | grep -o '#[0-9]*'
|
|
||||||
|
|
||||||
# Check if dependencies are closed
|
|
||||||
gh issue view <dep-number> --json state
|
|
||||||
```
|
|
||||||
|
|
||||||
If dependencies are NOT closed: **STOP**. Work on dependencies first or inform the user.
|
|
||||||
|
|
||||||
**Step 1.3: Read Referenced Documentation**
|
|
||||||
|
|
||||||
The ticket's "Context" section lists docs to read. Read ALL of them:
|
|
||||||
```bash
|
|
||||||
# Example: if ticket says "Read first: docs/jobs.md"
|
|
||||||
cat docs/jobs.md
|
|
||||||
```
|
|
||||||
|
|
||||||
**Step 1.4: Read Related Existing Code**
|
|
||||||
|
|
||||||
If the ticket depends on other issues, read the code they produced:
|
|
||||||
```bash
|
|
||||||
# Find relevant files
|
|
||||||
find src -name "*.java" | xargs grep -l "RelatedClass"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phase 2: PLAN (Still No Implementation Code)
|
|
||||||
|
|
||||||
**Step 2.1: List All Deliverables**
|
|
||||||
|
|
||||||
Extract from the ticket:
|
|
||||||
- [ ] Classes/files to create
|
|
||||||
- [ ] Methods to implement
|
|
||||||
- [ ] Tests to write
|
|
||||||
- [ ] Acceptance criteria to satisfy
|
|
||||||
|
|
||||||
**Step 2.2: Identify Test Cases**
|
|
||||||
|
|
||||||
From the "Tests Required" section, list every test:
|
|
||||||
```
|
|
||||||
Example:
|
|
||||||
- JobManagerTest.java
|
|
||||||
- createJob_withValidCommand_shouldReturnJobWithUniqueId
|
|
||||||
- createJob_withNullCommand_shouldThrowNullPointerException
|
|
||||||
- findJob_withExistingId_shouldReturnJob
|
|
||||||
- findJob_withMissingId_shouldReturnEmpty
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phase 3: TEST (Write Tests FIRST)
|
|
||||||
|
|
||||||
```
|
|
||||||
┌─────────────────────────────────────────────────────────┐
|
|
||||||
│ Write ALL tests before writing ANY implementation code │
|
|
||||||
└─────────────────────────────────────────────────────────┘
|
|
||||||
```
|
|
||||||
|
|
||||||
**Step 3.1: Create Test File**
|
|
||||||
```java
|
|
||||||
// src/test/java/com/samsonmedia/barn/<package>/<Class>Test.java
|
|
||||||
class JobManagerTest {
|
|
||||||
@Test
|
|
||||||
void methodName_condition_expectedResult() {
|
|
||||||
// Arrange
|
|
||||||
// Act
|
|
||||||
// Assert - use AssertJ
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Step 3.2: Write ALL Test Cases**
|
|
||||||
|
|
||||||
Write tests for:
|
|
||||||
1. Happy path (normal success)
|
|
||||||
2. Edge cases (empty, boundary values)
|
|
||||||
3. Error cases (null, invalid state)
|
|
||||||
4. Every acceptance criterion
|
|
||||||
|
|
||||||
**Step 3.3: Run Tests (Must FAIL)**
|
|
||||||
```bash
|
|
||||||
mvn test -Dtest=<TestClass>
|
|
||||||
# Expected: FAILURE (code not implemented yet)
|
|
||||||
```
|
|
||||||
|
|
||||||
If tests pass before implementation, the tests are wrong.
|
|
||||||
|
|
||||||
### Phase 4: IMPLEMENT (Now Write Code)
|
|
||||||
|
|
||||||
**Step 4.1: Implement Minimum Code**
|
|
||||||
|
|
||||||
Write the minimum code to make ONE test pass at a time:
|
|
||||||
```bash
|
|
||||||
# After each small change
|
|
||||||
mvn test -Dtest=<TestClass>#<testMethod>
|
|
||||||
```
|
|
||||||
|
|
||||||
**Step 4.2: Follow Coding Standards**
|
|
||||||
|
|
||||||
Every file must:
|
|
||||||
- Have no wildcard imports
|
|
||||||
- Use `Optional<T>` not null returns
|
|
||||||
- Use `Objects.requireNonNull()` for parameters
|
|
||||||
- Use `final` for immutable fields
|
|
||||||
- Have proper Javadoc on public methods
|
|
||||||
|
|
||||||
**Step 4.3: Iterate Until All Tests Pass**
|
|
||||||
```bash
|
|
||||||
mvn test -Dtest=<TestClass>
|
|
||||||
# Expected: SUCCESS for all tests
|
|
||||||
```
|
|
||||||
|
|
||||||
### Phase 5: VERIFY (Full Quality Check)
|
|
||||||
|
|
||||||
**Step 5.1: Run Full Verification**
|
|
||||||
```bash
|
|
||||||
mvn verify
|
|
||||||
```
|
|
||||||
|
|
||||||
This MUST pass:
|
|
||||||
- ✓ Checkstyle (formatting)
|
|
||||||
- ✓ Compilation (no warnings)
|
|
||||||
- ✓ All unit tests
|
|
||||||
- ✓ SpotBugs (no bugs)
|
|
||||||
- ✓ PMD (no violations)
|
|
||||||
- ✓ JaCoCo (80%+ coverage)
|
|
||||||
|
|
||||||
**Step 5.2: Check Acceptance Criteria**
|
|
||||||
|
|
||||||
Go through EVERY checkbox in the ticket:
|
|
||||||
```
|
|
||||||
- [ ] Criterion 1 → Verify manually or with test
|
|
||||||
- [ ] Criterion 2 → Verify manually or with test
|
|
||||||
...
|
|
||||||
```
|
|
||||||
|
|
||||||
**Step 5.3: Fix Any Issues**
|
|
||||||
|
|
||||||
If `mvn verify` fails:
|
|
||||||
1. Read the error message
|
|
||||||
2. Fix the issue
|
|
||||||
3. Run `mvn verify` again
|
|
||||||
4. Repeat until clean
|
|
||||||
|
|
||||||
### Phase 6: COMPLETE (Commit and Close)
|
|
||||||
|
|
||||||
**Step 6.1: Commit with Conventional Message**
|
|
||||||
```bash
|
|
||||||
git add .
|
|
||||||
git commit -m "feat(<scope>): <description>
|
|
||||||
|
|
||||||
Implements #<issue-number>
|
|
||||||
|
|
||||||
- Added <component>
|
|
||||||
- Implemented <feature>
|
|
||||||
- Tests for <functionality>
|
|
||||||
|
|
||||||
Co-Authored-By: Claude <noreply@anthropic.com>"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Step 6.2: Verify Commit**
|
|
||||||
```bash
|
|
||||||
# Ensure nothing is missed
|
|
||||||
git status
|
|
||||||
mvn verify # Run one final time
|
|
||||||
```
|
|
||||||
|
|
||||||
**Step 6.3: Close the Ticket**
|
|
||||||
```bash
|
|
||||||
gh issue close <issue-number> --comment "Implemented in commit <sha>"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Ticket Process Checklist
|
|
||||||
|
|
||||||
Copy this checklist for each ticket:
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
## Ticket #XX: <Title>
|
|
||||||
|
|
||||||
### Phase 1: READ
|
|
||||||
- [ ] Fetched ticket with `gh issue view`
|
|
||||||
- [ ] Read entire ticket description
|
|
||||||
- [ ] Checked all dependencies are closed
|
|
||||||
- [ ] Read all referenced documentation
|
|
||||||
- [ ] Read related existing code
|
|
||||||
|
|
||||||
### Phase 2: PLAN
|
|
||||||
- [ ] Listed all classes/files to create
|
|
||||||
- [ ] Listed all methods to implement
|
|
||||||
- [ ] Listed all test cases from ticket
|
|
||||||
|
|
||||||
### Phase 3: TEST
|
|
||||||
- [ ] Created test file(s)
|
|
||||||
- [ ] Wrote all test cases
|
|
||||||
- [ ] Tests fail (code not implemented)
|
|
||||||
|
|
||||||
### Phase 4: IMPLEMENT
|
|
||||||
- [ ] Implemented code to pass tests
|
|
||||||
- [ ] All tests pass
|
|
||||||
- [ ] Followed coding standards
|
|
||||||
|
|
||||||
### Phase 5: VERIFY
|
|
||||||
- [ ] `mvn verify` passes
|
|
||||||
- [ ] All acceptance criteria checked
|
|
||||||
- [ ] No TODO/FIXME without issue
|
|
||||||
|
|
||||||
### Phase 6: COMPLETE
|
|
||||||
- [ ] Committed with conventional message
|
|
||||||
- [ ] Closed ticket with `gh issue close`
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Critical Requirements
|
|
||||||
|
|
||||||
### 1. ALWAYS Write Tests First
|
|
||||||
|
|
||||||
**Every code change MUST include automated tests.** No exceptions.
|
|
||||||
|
|
||||||
```
|
|
||||||
Code without tests = Incomplete work
|
|
||||||
```
|
|
||||||
|
|
||||||
Before implementing any feature or fix:
|
|
||||||
1. Write failing tests that define the expected behavior
|
|
||||||
2. Implement the code to make tests pass
|
|
||||||
3. Run `mvn verify` to ensure all checks pass
|
|
||||||
4. Only then consider the work complete
|
|
||||||
|
|
||||||
### 2. ALWAYS Validate with Tests
|
|
||||||
|
|
||||||
After writing code, ALWAYS run:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
mvn verify
|
|
||||||
```
|
|
||||||
|
|
||||||
This runs:
|
|
||||||
- Compilation with `-Werror` (warnings are errors)
|
|
||||||
- Checkstyle (code formatting)
|
|
||||||
- Unit tests
|
|
||||||
- SpotBugs (bug detection)
|
|
||||||
- PMD (static analysis)
|
|
||||||
- JaCoCo (coverage check - must be 80%+)
|
|
||||||
|
|
||||||
**Do NOT consider code complete until `mvn verify` passes.**
|
|
||||||
|
|
||||||
### 3. ALWAYS Follow Coding Standards
|
|
||||||
|
|
||||||
Read `docs/coding-standards.md` before writing code. Key rules:
|
|
||||||
- 4 spaces indentation, 120 char line limit
|
|
||||||
- No wildcard imports
|
|
||||||
- Use `Optional<T>` instead of returning `null`
|
|
||||||
- Use `Objects.requireNonNull()` for constructor params
|
|
||||||
- Use `final` for fields that don't change
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Project Overview
|
|
||||||
|
|
||||||
Barn is a cross-platform job daemon for managing long-running media processing tasks (FFmpeg, WebDAV transfers). It runs as an OS service on Windows, macOS, and Linux.
|
|
||||||
|
|
||||||
## Technology Stack
|
|
||||||
|
|
||||||
- **Language**: Java 21+
|
|
||||||
- **Build**: Maven
|
|
||||||
- **Native Image**: GraalVM Native Image
|
|
||||||
- **Code Style**: Checkstyle (Google Java Style)
|
|
||||||
- **Static Analysis**: SpotBugs, PMD
|
|
||||||
- **Testing**: JUnit 5, Mockito, AssertJ
|
|
||||||
- **Coverage**: JaCoCo (80% minimum)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Testing Requirements (MANDATORY)
|
|
||||||
|
|
||||||
### Test Coverage Requirements
|
|
||||||
|
|
||||||
| Type | Minimum | Target |
|
|
||||||
|------|---------|--------|
|
|
||||||
| Line coverage | 80% | 90%+ |
|
|
||||||
| Branch coverage | 70% | 80%+ |
|
|
||||||
| New code | 100% | 100% |
|
|
||||||
|
|
||||||
### Test Naming Convention
|
|
||||||
|
|
||||||
```java
|
|
||||||
// Pattern: methodName_condition_expectedResult
|
|
||||||
@Test
|
|
||||||
void createJob_withValidCommand_shouldReturnJobWithUniqueId() { }
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void createJob_withNullCommand_shouldThrowNullPointerException() { }
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void processJob_whenServiceNotRunning_shouldThrowIllegalStateException() { }
|
|
||||||
```
|
|
||||||
|
|
||||||
### Test Structure (AAA Pattern)
|
|
||||||
|
|
||||||
```java
|
|
||||||
@Test
|
|
||||||
void findJob_withExistingId_shouldReturnJob() {
|
|
||||||
// Arrange
|
|
||||||
var manager = new JobManager(testConfig);
|
|
||||||
var job = manager.createJob(new Command("echo", "test"));
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = manager.findJob(job.getId());
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
assertThat(result).isPresent();
|
|
||||||
assertThat(result.get().getId()).isEqualTo(job.getId());
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### What to Test
|
|
||||||
|
|
||||||
For EVERY class you create or modify:
|
|
||||||
|
|
||||||
1. **Happy path** - Normal successful operation
|
|
||||||
2. **Edge cases** - Empty inputs, boundary values
|
|
||||||
3. **Error cases** - Null inputs, invalid states
|
|
||||||
4. **Integration** - Component interactions
|
|
||||||
|
|
||||||
### Test File Location
|
|
||||||
|
|
||||||
```
|
|
||||||
src/
|
|
||||||
main/java/com/samsonmedia/barn/
|
|
||||||
jobs/
|
|
||||||
JobManager.java
|
|
||||||
test/java/com/samsonmedia/barn/
|
|
||||||
jobs/
|
|
||||||
JobManagerTest.java # Unit tests
|
|
||||||
JobManagerIT.java # Integration tests
|
|
||||||
```
|
|
||||||
|
|
||||||
### Running Tests
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Run all tests
|
|
||||||
mvn test
|
|
||||||
|
|
||||||
# Run specific test class
|
|
||||||
mvn test -Dtest=JobManagerTest
|
|
||||||
|
|
||||||
# Run with coverage report
|
|
||||||
mvn test jacoco:report
|
|
||||||
# View: target/site/jacoco/index.html
|
|
||||||
|
|
||||||
# Run full verification (ALWAYS do this before committing)
|
|
||||||
mvn verify
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Workflow for Every Code Change
|
|
||||||
|
|
||||||
### Step 1: Understand the Requirement
|
|
||||||
- Read relevant docs
|
|
||||||
- Understand existing code patterns
|
|
||||||
|
|
||||||
### Step 2: Write Tests FIRST
|
|
||||||
```java
|
|
||||||
// Write test that defines expected behavior
|
|
||||||
@Test
|
|
||||||
void newFeature_shouldDoExpectedThing() {
|
|
||||||
// Arrange
|
|
||||||
var component = new Component();
|
|
||||||
|
|
||||||
// Act
|
|
||||||
var result = component.newFeature();
|
|
||||||
|
|
||||||
// Assert
|
|
||||||
assertThat(result).isEqualTo(expected);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 3: Run Tests (Should Fail)
|
|
||||||
```bash
|
|
||||||
mvn test -Dtest=ComponentTest#newFeature_shouldDoExpectedThing
|
|
||||||
# Expected: FAILURE (test written, code not yet implemented)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 4: Implement the Code
|
|
||||||
Write minimal code to make the test pass.
|
|
||||||
|
|
||||||
### Step 5: Run Tests (Should Pass)
|
|
||||||
```bash
|
|
||||||
mvn test -Dtest=ComponentTest#newFeature_shouldDoExpectedThing
|
|
||||||
# Expected: SUCCESS
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 6: Run Full Verification
|
|
||||||
```bash
|
|
||||||
mvn verify
|
|
||||||
# Must pass ALL checks:
|
|
||||||
# - Checkstyle
|
|
||||||
# - Compilation
|
|
||||||
# - All tests
|
|
||||||
# - SpotBugs
|
|
||||||
# - PMD
|
|
||||||
# - Coverage thresholds
|
|
||||||
```
|
|
||||||
|
|
||||||
### Step 7: Only THEN Consider Complete
|
|
||||||
If `mvn verify` fails, fix the issues and repeat.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Code Standards Summary
|
|
||||||
|
|
||||||
### Formatting
|
|
||||||
- 4 spaces indentation (no tabs)
|
|
||||||
- 120 character line limit
|
|
||||||
- K&R brace style (opening brace on same line)
|
|
||||||
- Static imports first, then regular imports, alphabetically
|
|
||||||
|
|
||||||
### Naming
|
|
||||||
- Packages: `lowercase`
|
|
||||||
- Classes/Interfaces: `PascalCase`
|
|
||||||
- Methods/Variables: `camelCase`
|
|
||||||
- Constants: `SCREAMING_SNAKE_CASE`
|
|
||||||
|
|
||||||
### Java Idioms
|
|
||||||
```java
|
|
||||||
// Use final for immutable fields
|
|
||||||
private final Config config;
|
|
||||||
|
|
||||||
// Use Optional for nullable returns
|
|
||||||
public Optional<Job> findJob(String id) {
|
|
||||||
return Optional.ofNullable(jobs.get(id));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate constructor params
|
|
||||||
public JobManager(Config config) {
|
|
||||||
this.config = Objects.requireNonNull(config, "config must not be null");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Use records for value objects
|
|
||||||
public record Job(String id, JobState state, Instant createdAt) {}
|
|
||||||
|
|
||||||
// Use switch expressions
|
|
||||||
String status = switch (state) {
|
|
||||||
case QUEUED -> "Waiting";
|
|
||||||
case RUNNING -> "Executing";
|
|
||||||
case FAILED -> "Failed";
|
|
||||||
case SUCCEEDED -> "Done";
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
### Error Handling
|
|
||||||
```java
|
|
||||||
// Use Optional, not null
|
|
||||||
public Optional<Job> findJob(String id);
|
|
||||||
|
|
||||||
// Validate preconditions
|
|
||||||
public void processJob(Job job) {
|
|
||||||
Objects.requireNonNull(job, "job");
|
|
||||||
if (job.getState() != JobState.QUEUED) {
|
|
||||||
throw new IllegalStateException("Job must be QUEUED");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create domain exceptions
|
|
||||||
public class JobNotFoundException extends RuntimeException {
|
|
||||||
public JobNotFoundException(String jobId) {
|
|
||||||
super("Job not found: " + jobId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Architecture Principles
|
|
||||||
|
|
||||||
### Filesystem as Database
|
|
||||||
- Job state stored in `/tmp/barn/jobs/<job-id>/`
|
|
||||||
- Use atomic file operations
|
|
||||||
- Human-readable plain text files
|
|
||||||
- No external database dependencies
|
|
||||||
|
|
||||||
### Cross-Platform
|
|
||||||
- Use `System.getProperty("java.io.tmpdir")` for temp paths
|
|
||||||
- Avoid platform-specific commands
|
|
||||||
- Test on Windows, macOS, and Linux
|
|
||||||
|
|
||||||
### GraalVM Native Image
|
|
||||||
- Avoid reflection where possible
|
|
||||||
- Register any reflection in `reflect-config.json`
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## File Structure
|
|
||||||
|
|
||||||
```
|
|
||||||
barn/
|
|
||||||
src/
|
|
||||||
main/java/com/samsonmedia/barn/
|
|
||||||
Main.java # Entry point
|
|
||||||
cli/ # CLI commands (picocli)
|
|
||||||
config/ # Configuration parsing
|
|
||||||
jobs/ # Job management
|
|
||||||
service/ # Daemon/service logic
|
|
||||||
state/ # Filesystem state management
|
|
||||||
test/java/com/samsonmedia/barn/
|
|
||||||
# Mirror structure with Test suffix
|
|
||||||
config/
|
|
||||||
checkstyle/ # Checkstyle rules
|
|
||||||
spotbugs/ # SpotBugs exclusions
|
|
||||||
pmd/ # PMD ruleset
|
|
||||||
docs/ # Documentation
|
|
||||||
pom.xml # Maven build
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Commit Checklist
|
|
||||||
|
|
||||||
Before EVERY commit:
|
|
||||||
|
|
||||||
- [ ] Tests written for new/changed code
|
|
||||||
- [ ] `mvn verify` passes
|
|
||||||
- [ ] No `TODO` or `FIXME` without tracking issue
|
|
||||||
- [ ] Javadoc for public API
|
|
||||||
- [ ] Commit message follows Conventional Commits format
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Commit message format
|
|
||||||
feat(jobs): add retry mechanism for failed jobs
|
|
||||||
fix(cli): handle spaces in file paths
|
|
||||||
test(jobs): add integration tests for job lifecycle
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## What NOT to Do
|
|
||||||
|
|
||||||
- **Don't skip tests** - Every change needs tests
|
|
||||||
- **Don't commit without `mvn verify`** - Ensures all checks pass
|
|
||||||
- **Don't return `null`** - Use `Optional<T>` instead
|
|
||||||
- **Don't catch `Exception`** - Catch specific exceptions
|
|
||||||
- **Don't use `System.out.println`** - Use SLF4J logging
|
|
||||||
- **Don't use wildcard imports** - Import specific classes
|
|
||||||
- **Don't use raw types** - Always specify generics
|
|
||||||
- **Don't ignore warnings** - Fix them (they're errors with `-Werror`)
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Quick Reference
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# Build
|
|
||||||
mvn package
|
|
||||||
|
|
||||||
# Test
|
|
||||||
mvn test
|
|
||||||
|
|
||||||
# Full verification (ALWAYS before commit)
|
|
||||||
mvn verify
|
|
||||||
|
|
||||||
# Coverage report
|
|
||||||
mvn test jacoco:report
|
|
||||||
|
|
||||||
# Fast build (skip checks - use sparingly)
|
|
||||||
mvn package -Pfast
|
|
||||||
|
|
||||||
# Specific test
|
|
||||||
mvn test -Dtest=JobManagerTest
|
|
||||||
|
|
||||||
# View SpotBugs in GUI
|
|
||||||
mvn compile spotbugs:gui
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Pre-Release Testing Checklist (MANDATORY)
|
|
||||||
|
|
||||||
Before creating ANY release tag, you MUST test ALL subcommands with the native binary locally.
|
|
||||||
|
|
||||||
### Prerequisites
|
|
||||||
|
|
||||||
1. **Build the native image locally:**
|
|
||||||
```bash
|
|
||||||
export JAVA_HOME="/Library/Java/JavaVirtualMachines/graalvm-25.jdk/Contents/Home"
|
|
||||||
mvn package -Pnative -DskipTests -Dspotbugs.skip=true -Dpmd.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Verify the binary exists:**
|
|
||||||
```bash
|
|
||||||
ls -la target/barn
|
|
||||||
```
|
|
||||||
|
|
||||||
### Test Every Subcommand
|
|
||||||
|
|
||||||
Run each command and verify the expected output. **Do NOT skip any command.**
|
|
||||||
|
|
||||||
#### Basic Commands
|
|
||||||
```bash
|
|
||||||
# Should show usage/help
|
|
||||||
./target/barn
|
|
||||||
# Expected: Shows "Usage: barn [-hV] [COMMAND]" and lists all subcommands
|
|
||||||
|
|
||||||
./target/barn --help
|
|
||||||
# Expected: Same as above
|
|
||||||
|
|
||||||
./target/barn --version
|
|
||||||
# Expected: Shows "barn X.Y.Z"
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Service Commands (Start service first)
|
|
||||||
```bash
|
|
||||||
# Stop any existing service
|
|
||||||
./target/barn service stop 2>/dev/null || true
|
|
||||||
|
|
||||||
# Start the service
|
|
||||||
./target/barn service start
|
|
||||||
# Expected: "Barn service started (PID: XXXXX)"
|
|
||||||
|
|
||||||
# Check service status
|
|
||||||
./target/barn service status
|
|
||||||
# Expected: Shows "Status: running", PID, uptime, job counts
|
|
||||||
|
|
||||||
# Test reload (reloads config without restart)
|
|
||||||
./target/barn service reload
|
|
||||||
# Expected: "Configuration reloaded"
|
|
||||||
|
|
||||||
# View logs
|
|
||||||
./target/barn service logs
|
|
||||||
# Expected: Shows recent log entries or "No logs found"
|
|
||||||
|
|
||||||
# Restart the service
|
|
||||||
./target/barn service restart
|
|
||||||
# Expected: "Barn service restarted"
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Job Commands (Service must be running)
|
|
||||||
```bash
|
|
||||||
# Run a test job
|
|
||||||
./target/barn run -- echo "test from native binary"
|
|
||||||
# Expected: "Job created: job-XXXXXXXX" with state: queued
|
|
||||||
|
|
||||||
# Wait a moment, then check status
|
|
||||||
sleep 2
|
|
||||||
./target/barn status
|
|
||||||
# Expected: Shows table with jobs, including the new job as "succeeded"
|
|
||||||
|
|
||||||
# Get the job ID from status output, then describe it
|
|
||||||
./target/barn describe <job-id>
|
|
||||||
# Expected: Shows detailed job info including timestamps, exit code, files
|
|
||||||
|
|
||||||
# Check resource usage
|
|
||||||
./target/barn usage <job-id>
|
|
||||||
# Expected: Shows CPU/memory/disk usage samples
|
|
||||||
|
|
||||||
# Test kill on a non-running job (should fail gracefully)
|
|
||||||
./target/barn kill <job-id>
|
|
||||||
# Expected: "Error: Job is not running: SUCCEEDED"
|
|
||||||
|
|
||||||
# Clean with dry-run
|
|
||||||
./target/barn clean --dry-run
|
|
||||||
# Expected: "Would clean X jobs:" followed by list
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Config Commands
|
|
||||||
```bash
|
|
||||||
./target/barn config show
|
|
||||||
# Expected: Shows configuration with all sections (service, jobs, cleanup, storage)
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Autocompletion Commands
|
|
||||||
```bash
|
|
||||||
./target/barn autocompletion --bash | head -5
|
|
||||||
# Expected: Shows bash completion script starting with "#!/usr/bin/env bash"
|
|
||||||
|
|
||||||
./target/barn autocompletion --zsh | head -5
|
|
||||||
# Expected: Shows zsh completion script
|
|
||||||
```
|
|
||||||
|
|
||||||
#### Service Stop (Clean up)
|
|
||||||
```bash
|
|
||||||
./target/barn service stop
|
|
||||||
# Expected: "Barn service stopped"
|
|
||||||
|
|
||||||
./target/barn service status
|
|
||||||
# Expected: "Barn service is not running"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Checklist Summary
|
|
||||||
|
|
||||||
Copy this checklist and verify each item:
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
## Pre-Release Testing for vX.Y.Z
|
|
||||||
|
|
||||||
### Build
|
|
||||||
- [ ] Native image builds successfully
|
|
||||||
- [ ] Binary exists at target/barn
|
|
||||||
|
|
||||||
### Basic Commands
|
|
||||||
- [ ] `barn` shows help
|
|
||||||
- [ ] `barn --help` shows help
|
|
||||||
- [ ] `barn --version` shows correct version
|
|
||||||
|
|
||||||
### Service Commands
|
|
||||||
- [ ] `barn service start` starts the service
|
|
||||||
- [ ] `barn service status` shows running status
|
|
||||||
- [ ] `barn service reload` reloads config
|
|
||||||
- [ ] `barn service logs` shows logs
|
|
||||||
- [ ] `barn service restart` restarts cleanly
|
|
||||||
- [ ] `barn service stop` stops the service
|
|
||||||
|
|
||||||
### Job Commands (with service running)
|
|
||||||
- [ ] `barn run -- echo test` creates a job
|
|
||||||
- [ ] `barn status` shows job list
|
|
||||||
- [ ] `barn describe <id>` shows job details
|
|
||||||
- [ ] `barn usage <id>` shows resource usage
|
|
||||||
- [ ] `barn kill <id>` handles non-running job gracefully
|
|
||||||
- [ ] `barn clean --dry-run` shows what would be cleaned
|
|
||||||
|
|
||||||
### Config Commands
|
|
||||||
- [ ] `barn config show` displays configuration
|
|
||||||
|
|
||||||
### Autocompletion
|
|
||||||
- [ ] `barn autocompletion --bash` generates bash script
|
|
||||||
- [ ] `barn autocompletion --zsh` generates zsh script
|
|
||||||
|
|
||||||
### Final
|
|
||||||
- [ ] All commands return expected output
|
|
||||||
- [ ] No crashes or exceptions
|
|
||||||
- [ ] Service starts and stops cleanly
|
|
||||||
```
|
|
||||||
|
|
||||||
### Only After All Tests Pass
|
|
||||||
|
|
||||||
1. Commit any fixes
|
|
||||||
2. Push to main
|
|
||||||
3. Wait for CI to pass
|
|
||||||
4. Create the release tag: `git tag vX.Y.Z && git push origin vX.Y.Z`
|
|
||||||
|
|
||||||
**NEVER create a release tag without completing this checklist.**
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Questions to Ask Before Implementing
|
|
||||||
|
|
||||||
1. Have I read the relevant documentation?
|
|
||||||
2. Have I written tests that define the expected behavior?
|
|
||||||
3. Does this work on Windows, macOS, AND Linux?
|
|
||||||
4. Will this survive a crash/restart?
|
|
||||||
5. Can the state be manually inspected in the filesystem?
|
|
||||||
6. Does `mvn verify` pass?
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Working with GitHub Issues
|
|
||||||
|
|
||||||
### Viewing the Backlog
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# List all open issues
|
|
||||||
gh issue list
|
|
||||||
|
|
||||||
# List issues by milestone
|
|
||||||
gh issue list --milestone "M1: Foundation"
|
|
||||||
|
|
||||||
# List issues by label
|
|
||||||
gh issue list --label "foundation"
|
|
||||||
|
|
||||||
# View specific issue
|
|
||||||
gh issue view 1
|
|
||||||
```
|
|
||||||
|
|
||||||
### Dependency Graph
|
|
||||||
|
|
||||||
Issues must be completed in dependency order. The milestones define the general order:
|
|
||||||
|
|
||||||
```
|
|
||||||
M1: Foundation (#1, #2, #3, #4, #22)
|
|
||||||
↓
|
|
||||||
M2: Job Execution (#5, #6, #7, #20)
|
|
||||||
↓
|
|
||||||
M3: CLI Commands (#8, #9, #10, #11, #12, #13, #21)
|
|
||||||
↓
|
|
||||||
M4: Service Infrastructure (#14, #15, #16)
|
|
||||||
↓
|
|
||||||
M5: Platform Integration (#17, #18, #19)
|
|
||||||
```
|
|
||||||
|
|
||||||
**Recommended order within M1:**
|
|
||||||
```
|
|
||||||
#1 (project structure)
|
|
||||||
→ #22 (logging)
|
|
||||||
→ #2 (configuration)
|
|
||||||
→ #3 (filesystem state)
|
|
||||||
→ #4 (job model)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Starting a New Ticket
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 1. Check what's ready to work on (no open dependencies)
|
|
||||||
gh issue list --milestone "M1: Foundation" --state open
|
|
||||||
|
|
||||||
# 2. Pick the next ticket with closed dependencies
|
|
||||||
gh issue view 1
|
|
||||||
|
|
||||||
# 3. Follow the Ticket Implementation Process above
|
|
||||||
```
|
|
||||||
|
|
||||||
### Progress Tracking
|
|
||||||
|
|
||||||
After completing a ticket:
|
|
||||||
```bash
|
|
||||||
# Close with comment
|
|
||||||
gh issue close <number> --comment "Implemented in commit abc123"
|
|
||||||
|
|
||||||
# Verify milestone progress
|
|
||||||
gh issue list --milestone "M1: Foundation"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Emergency Procedures
|
|
||||||
|
|
||||||
### If `mvn verify` Fails
|
|
||||||
|
|
||||||
1. **Read the error** - Don't guess, read the actual message
|
|
||||||
2. **Identify the phase** - Checkstyle? Compile? Test? SpotBugs? PMD? JaCoCo?
|
|
||||||
3. **Fix incrementally** - Run just that check until it passes:
|
|
||||||
```bash
|
|
||||||
mvn checkstyle:check # Formatting issues
|
|
||||||
mvn compile # Compilation errors
|
|
||||||
mvn test # Test failures
|
|
||||||
mvn spotbugs:check # Bug detection
|
|
||||||
mvn pmd:check # Static analysis
|
|
||||||
mvn jacoco:check # Coverage issues
|
|
||||||
```
|
|
||||||
4. **Run full verify again** - `mvn verify`
|
|
||||||
|
|
||||||
### If Tests Won't Pass
|
|
||||||
|
|
||||||
1. **Check the test is correct** - Is the expected behavior right?
|
|
||||||
2. **Check dependencies** - Is required code from other tickets present?
|
|
||||||
3. **Check test isolation** - Does the test depend on external state?
|
|
||||||
4. **Run single test** - `mvn test -Dtest=ClassName#methodName`
|
|
||||||
|
|
||||||
### If Stuck on a Ticket
|
|
||||||
|
|
||||||
1. **Re-read the ticket** - Often the answer is in the description
|
|
||||||
2. **Check Implementation Notes** - Specific guidance is provided
|
|
||||||
3. **Check referenced docs** - Context section lists what to read
|
|
||||||
4. **Look at similar code** - How did other tickets solve similar problems?
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Ticket Template Reference
|
|
||||||
|
|
||||||
Every ticket follows this structure:
|
|
||||||
|
|
||||||
```markdown
|
|
||||||
## Overview
|
|
||||||
Brief description of what to implement.
|
|
||||||
|
|
||||||
## Context
|
|
||||||
- **Read first**: docs to read before starting
|
|
||||||
- **Depends on**: prerequisite tickets
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
### 1. Component Name
|
|
||||||
Detailed requirements with code examples.
|
|
||||||
|
|
||||||
### 2. Another Component
|
|
||||||
More requirements...
|
|
||||||
|
|
||||||
## Tests Required
|
|
||||||
- TestClass1.java: description
|
|
||||||
- TestClass2.java: description
|
|
||||||
|
|
||||||
## Acceptance Criteria
|
|
||||||
- [ ] Criterion 1
|
|
||||||
- [ ] Criterion 2
|
|
||||||
- [ ] `mvn verify` passes
|
|
||||||
- [ ] Tests have 80%+ coverage
|
|
||||||
|
|
||||||
## Implementation Notes
|
|
||||||
Specific guidance, code patterns, edge cases.
|
|
||||||
|
|
||||||
## Definition of Done
|
|
||||||
Summary of completion requirements.
|
|
||||||
```
|
|
||||||
|
|
||||||
Use this structure to know exactly what's expected.
|
|
||||||
@@ -143,12 +143,15 @@ barn service status
|
|||||||
|
|
||||||
This project creates a simple CLI commandlet with sub-comands.
|
This project creates a simple CLI commandlet with sub-comands.
|
||||||
|
|
||||||
- `barn service {start|stop|resart|reload|status|logs"}"` - manages the barn service
|
- `barn service {start|stop|restart|reload|status|logs}` - manages the barn service
|
||||||
- `barn run {command}` - starts job
|
- `barn run {command}` - starts job
|
||||||
- `barn status` - gets the status of all jobs running
|
- `barn status` - gets the status of all jobs running
|
||||||
- `barn describe {jobId}` - collects all the info from /tmp and display it
|
- `barn describe {jobId}` - collects all the info from /tmp and display it
|
||||||
|
- `barn usage {jobId}` - shows resource usage (CPU, memory, disk) for a job
|
||||||
- `barn kill {jobId}` - kills a job
|
- `barn kill {jobId}` - kills a job
|
||||||
- `barn clean` - performs clean up
|
- `barn clean` - performs clean up
|
||||||
|
- `barn config install` - installs default configuration files
|
||||||
|
- `barn config show` - shows effective configuration
|
||||||
|
|
||||||
barn is just one binary for both the service and the client. the client uses IPC to communicate with the service.
|
barn is just one binary for both the service and the client. the client uses IPC to communicate with the service.
|
||||||
|
|
||||||
@@ -191,12 +194,13 @@ There needs to be a barn service in order to run jobs (unless you use --offline)
|
|||||||
|
|
||||||
### Adding jobs
|
### Adding jobs
|
||||||
|
|
||||||
`barn run --output=json --tag=downloading <cmd>}` takes in a command to run, starts a new process/thread, outputs the status of that job:
|
`barn run --output=json --tag=downloading <cmd>` takes in a command to run, starts a new process/thread, outputs the status of that job:
|
||||||
|
|
||||||
| File | Description |
|
| Field | Description |
|
||||||
|---------------|--------------------------------------------------------|
|
|---------------|--------------------------------------------------------|
|
||||||
| `job_id` | the job of the job |
|
| `job_id` | the job of the job |
|
||||||
| `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` |
|
| `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` |
|
||||||
|
| `load_level` | `HIGH`, `MEDIUM`, or `LOW` (auto-detected or manual) |
|
||||||
| `tag` | user defined string |
|
| `tag` | user defined string |
|
||||||
| `created_at` | Job creation timestamp |
|
| `created_at` | Job creation timestamp |
|
||||||
| `started_at` | Execution start timestamp |
|
| `started_at` | Execution start timestamp |
|
||||||
@@ -205,16 +209,21 @@ There needs to be a barn service in order to run jobs (unless you use --offline)
|
|||||||
| `error` | Human-readable failure reason |
|
| `error` | Human-readable failure reason |
|
||||||
| `pid` | OS process ID (best-effort) |
|
| `pid` | OS process ID (best-effort) |
|
||||||
| `heartbeat` | Last liveness update |
|
| `heartbeat` | Last liveness update |
|
||||||
|
| `retryCount` | Current retry attempt (0 if never retried) |
|
||||||
|
| `retryAt` | Timestamp for next retry attempt (null if not retrying)|
|
||||||
|
|
||||||
Users can tag job for the purpose of filtering using the --tag=string CLI option.
|
Users can tag jobs for the purpose of filtering using the `--tag=string` CLI option.
|
||||||
|
|
||||||
Developers can use the --offline command line option to test how the service behaves eg creating tmp files etc. This runs the same code as the service but without having to run the service
|
Jobs are automatically assigned a **load level** based on the command being run (see [Load Levels](#load-levels)). You can override this with `--load-level={high|medium|low}`.
|
||||||
|
|
||||||
|
Developers can use the `--offline` command line option to test how the service behaves (e.g., creating tmp files). This runs the same code as the service but without having to run the service.
|
||||||
|
|
||||||
**Example: `barn run --output=json -- echo "Hello World"`**
|
**Example: `barn run --output=json -- echo "Hello World"`**
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"id" : "job-6d368040",
|
"id" : "job-6d368040",
|
||||||
"state" : "QUEUED",
|
"state" : "QUEUED",
|
||||||
|
"loadLevel" : "MEDIUM",
|
||||||
"command" : [ "echo", "Hello World" ],
|
"command" : [ "echo", "Hello World" ],
|
||||||
"tag" : null,
|
"tag" : null,
|
||||||
"createdAt" : "2026-01-22T01:48:46.749629Z",
|
"createdAt" : "2026-01-22T01:48:46.749629Z",
|
||||||
@@ -236,12 +245,21 @@ Developers can use the --offline command line option to test how the service beh
|
|||||||
|
|
||||||
`barn status` gets the status of all jobs found in /tmp.
|
`barn status` gets the status of all jobs found in /tmp.
|
||||||
|
|
||||||
|
**Example: `barn status`**
|
||||||
|
```
|
||||||
|
ID STATE LOAD TAG CREATED EXIT PID RETRIES NEXT RETRY
|
||||||
|
job-6d368040 succeeded medium - 2026-01-22 01:48:46 0 17486 - -
|
||||||
|
|
||||||
|
Total: 1 job (1 succeeded)
|
||||||
|
```
|
||||||
|
|
||||||
**Example: `barn status --output=json`**
|
**Example: `barn status --output=json`**
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"jobs" : [ {
|
"jobs" : [ {
|
||||||
"id" : "job-6d368040",
|
"id" : "job-6d368040",
|
||||||
"state" : "SUCCEEDED",
|
"state" : "SUCCEEDED",
|
||||||
|
"loadLevel" : "MEDIUM",
|
||||||
"command" : [ "echo", "Hello World" ],
|
"command" : [ "echo", "Hello World" ],
|
||||||
"tag" : null,
|
"tag" : null,
|
||||||
"createdAt" : "2026-01-22T01:48:46.739979Z",
|
"createdAt" : "2026-01-22T01:48:46.739979Z",
|
||||||
@@ -306,9 +324,59 @@ Developers can use the --offline command line option to test how the service beh
|
|||||||
### Clean up jobs
|
### Clean up jobs
|
||||||
`barn clean` - removes completed jobs and cleans up old jobs (older than max_age config) from /tmp
|
`barn clean` - removes completed jobs and cleans up old jobs (older than max_age config) from /tmp
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Load Levels
|
||||||
|
|
||||||
|
Barn supports **per-level job limits** to allow concurrent execution of different types of jobs. For example, you can run multiple downloads while transcoding without overwhelming the system.
|
||||||
|
|
||||||
|
### Load Level Types
|
||||||
|
|
||||||
|
| Level | Default Max | Use Case |
|
||||||
|
|-------|-------------|----------|
|
||||||
|
| HIGH | 2 | CPU/GPU intensive (transcoding, encoding) |
|
||||||
|
| MEDIUM | 8 | General purpose commands |
|
||||||
|
| LOW | 32 | Network/IO intensive (downloads, uploads) |
|
||||||
|
|
||||||
|
### Auto-Classification
|
||||||
|
|
||||||
|
Jobs are automatically classified based on whitelist files in `/etc/barn/`:
|
||||||
|
|
||||||
|
- `high.load` - ffmpeg, ffprobe, handbrake, x264, x265, etc.
|
||||||
|
- `medium.load` - general commands (default if not matched)
|
||||||
|
- `low.load` - curl, wget, rclone, rsync, aria2c, etc.
|
||||||
|
|
||||||
|
### Manual Override
|
||||||
|
|
||||||
|
Force a specific load level for a job:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Run ffmpeg as LOW load (bypass normal HIGH classification)
|
||||||
|
barn run --load-level=low -- ffmpeg -i input.mp4 output.mp4
|
||||||
|
|
||||||
|
# Run curl as HIGH load (override normal LOW classification)
|
||||||
|
barn run --load-level=high -- curl -O https://example.com/file.zip
|
||||||
|
```
|
||||||
|
|
||||||
|
### Installing Default Config
|
||||||
|
|
||||||
|
Install default configuration files including load level whitelists:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Preview what would be installed
|
||||||
|
barn config install --show
|
||||||
|
|
||||||
|
# Install to system config directory (requires sudo on Linux/macOS)
|
||||||
|
sudo barn config install --force
|
||||||
|
```
|
||||||
|
|
||||||
|
See [Configuration](docs/config.md) for detailed load level configuration options.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
|
- [FFmpeg Integration Guide](docs/ffmpeg.md) explains FFmpeg-specific behavior (stdout/stderr, exit codes, recommended flags)
|
||||||
- [Barn Temporary Directory Layout](docs/jobs.md) describes how barn tracks jobs and storage
|
- [Barn Temporary Directory Layout](docs/jobs.md) describes how barn tracks jobs and storage
|
||||||
- [Barn Configuration](docs/config.md) describes configuration options, retry behavior, and cleanup policies
|
- [Barn Configuration](docs/config.md) describes configuration options, retry behavior, and cleanup policies
|
||||||
- [Development Guide](docs/development.md) covers local development setup and building from source
|
- [Development Guide](docs/development.md) covers local development setup and building from source
|
||||||
|
|||||||
+181
-10
@@ -6,13 +6,13 @@ This document describes the configuration file format and options for the Barn j
|
|||||||
|
|
||||||
## Configuration File Location
|
## Configuration File Location
|
||||||
|
|
||||||
Barn looks for configuration in the following locations (in order):
|
Barn uses system-wide configuration only:
|
||||||
|
|
||||||
| Platform | Path |
|
| Platform | Path |
|
||||||
|----------|------|
|
|----------|------|
|
||||||
| Linux | `/etc/barn/barn.conf` or `~/.config/barn/barn.conf` |
|
| Linux | `/etc/barn/barn.conf` |
|
||||||
| macOS | `/etc/barn/barn.conf` or `~/Library/Application Support/barn/barn.conf` |
|
| macOS | `/etc/barn/barn.conf` |
|
||||||
| Windows | `%PROGRAMDATA%\barn\barn.conf` or `%APPDATA%\barn\barn.conf` |
|
| Windows | `%PROGRAMDATA%\barn\barn.conf` |
|
||||||
|
|
||||||
You can also specify a config file explicitly:
|
You can also specify a config file explicitly:
|
||||||
|
|
||||||
@@ -29,10 +29,14 @@ Barn uses a simple key-value format (TOML-like):
|
|||||||
```toml
|
```toml
|
||||||
[service]
|
[service]
|
||||||
log_level = "info"
|
log_level = "info"
|
||||||
max_concurrent_jobs = 4
|
|
||||||
heartbeat_interval_seconds = 5
|
heartbeat_interval_seconds = 5
|
||||||
ipc_socket = "/tmp/barn/barn.sock"
|
ipc_socket = "/tmp/barn/barn.sock"
|
||||||
|
|
||||||
|
[load_levels]
|
||||||
|
max_high_jobs = 2
|
||||||
|
max_medium_jobs = 8
|
||||||
|
max_low_jobs = 32
|
||||||
|
|
||||||
[jobs]
|
[jobs]
|
||||||
default_timeout_seconds = 3600
|
default_timeout_seconds = 3600
|
||||||
max_retries = 3
|
max_retries = 3
|
||||||
@@ -57,13 +61,148 @@ max_disk_usage_gb = 50
|
|||||||
| Key | Type | Default | Description |
|
| Key | Type | Default | Description |
|
||||||
|-----|------|---------|-------------|
|
|-----|------|---------|-------------|
|
||||||
| `log_level` | string | `"info"` | Logging verbosity: `debug`, `info`, `warn`, `error` |
|
| `log_level` | string | `"info"` | Logging verbosity: `debug`, `info`, `warn`, `error` |
|
||||||
| `max_concurrent_jobs` | integer | `4` | Maximum jobs running simultaneously |
|
| `max_concurrent_jobs` | integer | `4` | **Deprecated.** Use `[load_levels]` instead. |
|
||||||
| `heartbeat_interval_seconds` | integer | `5` | How often running jobs update their heartbeat |
|
| `heartbeat_interval_seconds` | integer | `5` | How often running jobs update their heartbeat |
|
||||||
| `ipc_socket` | string | platform-specific | Path to the IPC socket for CLI communication |
|
| `ipc_socket` | string | platform-specific | Path to the IPC socket for CLI communication |
|
||||||
| `stale_heartbeat_threshold_seconds` | integer | `30` | Heartbeat age before a job is considered orphaned |
|
| `stale_heartbeat_threshold_seconds` | integer | `30` | Heartbeat age before a job is considered orphaned |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## Load Level Settings
|
||||||
|
|
||||||
|
Barn supports **per-level job limits** to allow concurrent execution of different types of jobs. For example, you can run multiple downloads (LOW load) while transcoding (HIGH load) without overwhelming the system.
|
||||||
|
|
||||||
|
### Configuration
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[load_levels]
|
||||||
|
max_high_jobs = 2
|
||||||
|
max_medium_jobs = 8
|
||||||
|
max_low_jobs = 32
|
||||||
|
```
|
||||||
|
|
||||||
|
| Key | Type | Default | Description |
|
||||||
|
|-----|------|---------|-------------|
|
||||||
|
| `max_high_jobs` | integer | `2` | Maximum concurrent HIGH load jobs (CPU/GPU intensive) |
|
||||||
|
| `max_medium_jobs` | integer | `8` | Maximum concurrent MEDIUM load jobs |
|
||||||
|
| `max_low_jobs` | integer | `32` | Maximum concurrent LOW load jobs (network/IO intensive) |
|
||||||
|
|
||||||
|
### Load Level Classification
|
||||||
|
|
||||||
|
Jobs are automatically classified into a load level based on **whitelist files** in the config directory. These files use a gitignore-style format.
|
||||||
|
|
||||||
|
#### Whitelist File Locations
|
||||||
|
|
||||||
|
| Platform | Directory |
|
||||||
|
|----------|-----------|
|
||||||
|
| Linux | `/etc/barn/` |
|
||||||
|
| macOS | `/etc/barn/` |
|
||||||
|
| Windows | `%PROGRAMDATA%\barn\` |
|
||||||
|
|
||||||
|
#### Whitelist Files
|
||||||
|
|
||||||
|
| File | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `high.load` | CPU/GPU intensive commands (transcoding, encoding) |
|
||||||
|
| `medium.load` | General purpose commands |
|
||||||
|
| `low.load` | Network/IO intensive commands (downloads, uploads) |
|
||||||
|
|
||||||
|
#### File Format
|
||||||
|
|
||||||
|
```
|
||||||
|
# Comments start with #
|
||||||
|
# Empty lines are ignored
|
||||||
|
|
||||||
|
# Match by executable name (any path)
|
||||||
|
ffmpeg
|
||||||
|
curl
|
||||||
|
|
||||||
|
# Match by full path
|
||||||
|
/usr/local/bin/custom-transcoder
|
||||||
|
|
||||||
|
# Match any executable in a directory (trailing slash)
|
||||||
|
/opt/encoders/
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Example `high.load`
|
||||||
|
|
||||||
|
```
|
||||||
|
# High load commands - CPU/GPU intensive (transcoding, encoding)
|
||||||
|
# Maximum concurrent: 2 (default)
|
||||||
|
ffmpeg
|
||||||
|
ffprobe
|
||||||
|
handbrake
|
||||||
|
HandBrakeCLI
|
||||||
|
x264
|
||||||
|
x265
|
||||||
|
av1an
|
||||||
|
svt-av1
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Example `low.load`
|
||||||
|
|
||||||
|
```
|
||||||
|
# Low load commands - Network/IO intensive (downloads, uploads)
|
||||||
|
# Maximum concurrent: 32 (default)
|
||||||
|
curl
|
||||||
|
wget
|
||||||
|
rclone
|
||||||
|
rsync
|
||||||
|
aria2c
|
||||||
|
scp
|
||||||
|
sftp
|
||||||
|
cadaver
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Classification Priority
|
||||||
|
|
||||||
|
1. Commands are checked against HIGH whitelist first
|
||||||
|
2. Then MEDIUM whitelist
|
||||||
|
3. Then LOW whitelist
|
||||||
|
4. If no match, defaults to **MEDIUM**
|
||||||
|
|
||||||
|
### Manual Load Level Override
|
||||||
|
|
||||||
|
You can override the auto-detected load level per job:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Force a command to run as LOW load
|
||||||
|
barn run --load-level=low -- ffmpeg -i input.mp4 output.mp4
|
||||||
|
|
||||||
|
# Force a command to run as HIGH load
|
||||||
|
barn run --load-level=high -- curl -O https://example.com/file.zip
|
||||||
|
```
|
||||||
|
|
||||||
|
### Installing Default Config Files
|
||||||
|
|
||||||
|
Use `barn config install` to create default configuration files:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Interactive installation (prompts for confirmation)
|
||||||
|
barn config install
|
||||||
|
|
||||||
|
# Force installation without prompts
|
||||||
|
barn config install --force
|
||||||
|
|
||||||
|
# Show what would be installed without writing
|
||||||
|
barn config install --show
|
||||||
|
```
|
||||||
|
|
||||||
|
This creates:
|
||||||
|
- `barn.conf` - Main configuration file
|
||||||
|
- `high.load` - High load whitelist (ffmpeg, etc.)
|
||||||
|
- `medium.load` - Medium load whitelist (empty)
|
||||||
|
- `low.load` - Low load whitelist (curl, wget, etc.)
|
||||||
|
|
||||||
|
### Backward Compatibility
|
||||||
|
|
||||||
|
When `[load_levels]` is not configured:
|
||||||
|
- The deprecated `max_concurrent_jobs` value is distributed proportionally across levels
|
||||||
|
- Ratio: 1 HIGH : 4 MEDIUM : 16 LOW
|
||||||
|
- Example: `max_concurrent_jobs = 21` → HIGH=1, MEDIUM=4, LOW=16
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Job Settings
|
## Job Settings
|
||||||
|
|
||||||
| Key | Type | Default | Description |
|
| Key | Type | Default | Description |
|
||||||
@@ -251,7 +390,11 @@ Pattern: `BARN_<SECTION>_<KEY>` (uppercase, underscores)
|
|||||||
```toml
|
```toml
|
||||||
[service]
|
[service]
|
||||||
log_level = "debug"
|
log_level = "debug"
|
||||||
max_concurrent_jobs = 2
|
|
||||||
|
[load_levels]
|
||||||
|
max_high_jobs = 1
|
||||||
|
max_medium_jobs = 2
|
||||||
|
max_low_jobs = 4
|
||||||
|
|
||||||
[jobs]
|
[jobs]
|
||||||
max_retries = 1
|
max_retries = 1
|
||||||
@@ -269,9 +412,13 @@ keep_failed_jobs = false
|
|||||||
```toml
|
```toml
|
||||||
[service]
|
[service]
|
||||||
log_level = "warn"
|
log_level = "warn"
|
||||||
max_concurrent_jobs = 8
|
|
||||||
heartbeat_interval_seconds = 10
|
heartbeat_interval_seconds = 10
|
||||||
|
|
||||||
|
[load_levels]
|
||||||
|
max_high_jobs = 4
|
||||||
|
max_medium_jobs = 16
|
||||||
|
max_low_jobs = 64
|
||||||
|
|
||||||
[jobs]
|
[jobs]
|
||||||
max_retries = 5
|
max_retries = 5
|
||||||
retry_delay_seconds = 60
|
retry_delay_seconds = 60
|
||||||
@@ -291,7 +438,12 @@ max_disk_usage_gb = 200
|
|||||||
|
|
||||||
```toml
|
```toml
|
||||||
[service]
|
[service]
|
||||||
max_concurrent_jobs = 1
|
log_level = "info"
|
||||||
|
|
||||||
|
[load_levels]
|
||||||
|
max_high_jobs = 1
|
||||||
|
max_medium_jobs = 1
|
||||||
|
max_low_jobs = 1
|
||||||
|
|
||||||
[jobs]
|
[jobs]
|
||||||
max_retries = 0
|
max_retries = 0
|
||||||
@@ -327,7 +479,24 @@ Settings that require a full restart:
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Validating Configuration
|
## Configuration Commands
|
||||||
|
|
||||||
|
### Install Default Configuration
|
||||||
|
|
||||||
|
Create default configuration files in the system config directory:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Interactive installation (prompts for confirmation)
|
||||||
|
barn config install
|
||||||
|
|
||||||
|
# Install without prompts
|
||||||
|
barn config install --force
|
||||||
|
|
||||||
|
# Preview what would be installed
|
||||||
|
barn config install --show
|
||||||
|
```
|
||||||
|
|
||||||
|
### Validate Configuration
|
||||||
|
|
||||||
Check your config file for errors:
|
Check your config file for errors:
|
||||||
|
|
||||||
@@ -336,6 +505,8 @@ barn config validate
|
|||||||
barn config validate --config /path/to/barn.conf
|
barn config validate --config /path/to/barn.conf
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Show Configuration
|
||||||
|
|
||||||
Show effective configuration (with defaults and overrides):
|
Show effective configuration (with defaults and overrides):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
+295
@@ -0,0 +1,295 @@
|
|||||||
|
# FFmpeg Integration Guide
|
||||||
|
|
||||||
|
This guide covers FFmpeg-specific behavior when running jobs with Barn.
|
||||||
|
|
||||||
|
## Programmatic Workflow
|
||||||
|
|
||||||
|
This section shows the complete process for running FFmpeg jobs programmatically (e.g., from a script or application over SSH).
|
||||||
|
|
||||||
|
### Step 1: Submit the Job
|
||||||
|
|
||||||
|
```bash
|
||||||
|
barn run --output=json -- ffmpeg -y -progress pipe:1 -threads 0 -i input.mkv -c:v libx264 output.mp4
|
||||||
|
```
|
||||||
|
|
||||||
|
Response:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id" : "job-cbe3e07f",
|
||||||
|
"state" : "QUEUED",
|
||||||
|
"command" : [ "ffmpeg", "-y", "-progress", "pipe:1", "-threads", "0", "-i", "input.mkv", "-c:v", "libx264", "output.mp4" ],
|
||||||
|
"tag" : null,
|
||||||
|
"createdAt" : "2026-01-22T10:13:34.121846Z",
|
||||||
|
"startedAt" : null,
|
||||||
|
"finishedAt" : null,
|
||||||
|
"exitCode" : null,
|
||||||
|
"error" : null,
|
||||||
|
"pid" : null,
|
||||||
|
"heartbeat" : null,
|
||||||
|
"retryCount" : 0,
|
||||||
|
"retryAt" : null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Save the `id` field for subsequent commands.
|
||||||
|
|
||||||
|
### Step 2: Poll for Status
|
||||||
|
|
||||||
|
Check job status with logs:
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```bash
|
||||||
|
barn describe job-cbe3e07f --logs --output=json
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output (while running):**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id" : "job-cbe3e07f",
|
||||||
|
"state" : "running",
|
||||||
|
"command" : [ "ffmpeg", "-y", "-progress", "pipe:1", "-threads", "0", "-i", "input.mkv", "-c:v", "libx264", "output.mp4" ],
|
||||||
|
"createdAt" : "2026-01-22T10:13:34.121180Z",
|
||||||
|
"startedAt" : "2026-01-22T10:13:34.347543Z",
|
||||||
|
"finishedAt" : null,
|
||||||
|
"pid" : 70923,
|
||||||
|
"exitCode" : null,
|
||||||
|
"error" : null,
|
||||||
|
"heartbeat" : "2026-01-22T10:13:34.347543Z",
|
||||||
|
"retryCount" : 0,
|
||||||
|
"retryAt" : null,
|
||||||
|
"paths" : {
|
||||||
|
"jobDir" : "/tmp/barn/jobs/job-cbe3e07f",
|
||||||
|
"workDir" : "/tmp/barn/jobs/job-cbe3e07f/work",
|
||||||
|
"logsDir" : "/tmp/barn/jobs/job-cbe3e07f/logs"
|
||||||
|
},
|
||||||
|
"logs" : {
|
||||||
|
"stdout" : "frame=90\nfps=120.5\nspeed=2.5x\nprogress=continue",
|
||||||
|
"stderr" : "ffmpeg version 8.0.1 Copyright (c) 2000-2025 the FFmpeg developers..."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output (succeeded):**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id" : "job-cbe3e07f",
|
||||||
|
"state" : "succeeded",
|
||||||
|
"command" : [ "ffmpeg", "-y", "-progress", "pipe:1", "-threads", "0", "-i", "input.mkv", "-c:v", "libx264", "output.mp4" ],
|
||||||
|
"createdAt" : "2026-01-22T10:13:34.121180Z",
|
||||||
|
"startedAt" : "2026-01-22T10:13:34.347543Z",
|
||||||
|
"finishedAt" : "2026-01-22T10:13:34.394959Z",
|
||||||
|
"pid" : 70923,
|
||||||
|
"exitCode" : 0,
|
||||||
|
"error" : null,
|
||||||
|
"heartbeat" : "2026-01-22T10:13:34.347543Z",
|
||||||
|
"retryCount" : 0,
|
||||||
|
"retryAt" : null,
|
||||||
|
"paths" : {
|
||||||
|
"jobDir" : "/tmp/barn/jobs/job-cbe3e07f",
|
||||||
|
"workDir" : "/tmp/barn/jobs/job-cbe3e07f/work",
|
||||||
|
"logsDir" : "/tmp/barn/jobs/job-cbe3e07f/logs"
|
||||||
|
},
|
||||||
|
"logs" : {
|
||||||
|
"stdout" : "frame=9000\nfps=120.5\nspeed=2.5x\nprogress=end",
|
||||||
|
"stderr" : "ffmpeg version 8.0.1...\n[libx264] encoded 9000 frames"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output (failed):**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id" : "job-12860505",
|
||||||
|
"state" : "failed",
|
||||||
|
"command" : [ "ffmpeg", "-y", "-progress", "pipe:1", "-i", "/invalid/path.mkv", "output.mp4" ],
|
||||||
|
"createdAt" : "2026-01-22T10:13:10.999377Z",
|
||||||
|
"startedAt" : "2026-01-22T10:13:11.347945Z",
|
||||||
|
"finishedAt" : "2026-01-22T10:13:11.364657Z",
|
||||||
|
"pid" : 70875,
|
||||||
|
"exitCode" : 1,
|
||||||
|
"error" : "Process exited with code 1",
|
||||||
|
"heartbeat" : "2026-01-22T10:13:11.347945Z",
|
||||||
|
"retryCount" : 0,
|
||||||
|
"retryAt" : null,
|
||||||
|
"paths" : {
|
||||||
|
"jobDir" : "/tmp/barn/jobs/job-12860505",
|
||||||
|
"workDir" : "/tmp/barn/jobs/job-12860505/work",
|
||||||
|
"logsDir" : "/tmp/barn/jobs/job-12860505/logs"
|
||||||
|
},
|
||||||
|
"logs" : {
|
||||||
|
"stdout" : "",
|
||||||
|
"stderr" : "ffmpeg version 8.0.1...\n/invalid/path.mkv: No such file or directory"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Understanding the Output
|
||||||
|
|
||||||
|
**Key fields to check:**
|
||||||
|
|
||||||
|
| Field | Description |
|
||||||
|
|-------|-------------|
|
||||||
|
| `state` | `queued`, `running`, `succeeded`, `failed`, `killed` |
|
||||||
|
| `exitCode` | `0` = success, non-zero = error, `null` = still running |
|
||||||
|
| `error` | Human-readable error message (when failed) |
|
||||||
|
| `logs.stdout` | FFmpeg progress output (with `-progress pipe:1`) |
|
||||||
|
| `logs.stderr` | FFmpeg errors and warnings |
|
||||||
|
|
||||||
|
**Progress fields in `logs.stdout`:**
|
||||||
|
|
||||||
|
| Field | Description |
|
||||||
|
|-------|-------------|
|
||||||
|
| `frame=N` | Current frame number |
|
||||||
|
| `fps=N` | Encoding speed (frames per second) |
|
||||||
|
| `speed=Nx` | Speed relative to realtime (e.g., `2.5x`) |
|
||||||
|
| `out_time=HH:MM:SS` | Current output timestamp |
|
||||||
|
| `bitrate=N` | Current bitrate |
|
||||||
|
| `progress=continue` | Job still running |
|
||||||
|
| `progress=end` | Job complete |
|
||||||
|
|
||||||
|
### Step 5: Kill a Running Job (Optional)
|
||||||
|
|
||||||
|
To stop a running job:
|
||||||
|
|
||||||
|
**Command:**
|
||||||
|
```bash
|
||||||
|
barn kill job-cbe3e07f --output=json
|
||||||
|
```
|
||||||
|
|
||||||
|
**Output:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id" : "job-cbe3e07f",
|
||||||
|
"state" : "killed",
|
||||||
|
"pid" : 70923,
|
||||||
|
"exitCode" : null,
|
||||||
|
"error" : "Job killed by user"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Summary
|
||||||
|
|
||||||
|
| Step | Command | Key Output Fields |
|
||||||
|
|------|---------|-------------------|
|
||||||
|
| Submit | `barn run --output=json -- ffmpeg ...` | `id`, `state` |
|
||||||
|
| Poll | `barn describe <id> --logs --output=json` | `state`, `exitCode`, `logs.stdout`, `logs.stderr` |
|
||||||
|
| Kill | `barn kill <id> --output=json` | `state` |
|
||||||
|
|
||||||
|
**State values:** `queued` → `running` → `succeeded` / `failed` / `killed`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Recommended FFmpeg Command
|
||||||
|
|
||||||
|
Use `-progress pipe:1` to output machine-readable progress to stdout:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
barn run -- ffmpeg -y -progress pipe:1 -threads 0 -i input.mkv -c:v libx264 output.mp4
|
||||||
|
```
|
||||||
|
|
||||||
|
This outputs structured key=value pairs to `stdout.log`:
|
||||||
|
|
||||||
|
```
|
||||||
|
frame=100
|
||||||
|
fps=120.5
|
||||||
|
stream_0_0_q=28.0
|
||||||
|
bitrate=4500.0kbits/s
|
||||||
|
total_size=5000000
|
||||||
|
out_time_us=4000000
|
||||||
|
out_time_ms=4000000
|
||||||
|
out_time=00:00:04.000000
|
||||||
|
dup_frames=0
|
||||||
|
drop_frames=0
|
||||||
|
speed=3.5x
|
||||||
|
progress=continue
|
||||||
|
```
|
||||||
|
|
||||||
|
The final block will have `progress=end` when complete.
|
||||||
|
|
||||||
|
Human-readable output (version info, warnings, errors) still goes to `stderr.log`.
|
||||||
|
|
||||||
|
### Recommended Flags
|
||||||
|
|
||||||
|
| Flag | Purpose |
|
||||||
|
|------|---------|
|
||||||
|
| `-y` | Overwrite output without asking |
|
||||||
|
| `-progress pipe:1` | Output machine-readable progress to stdout |
|
||||||
|
| `-threads 0` | Auto-detect optimal thread count |
|
||||||
|
|
||||||
|
### Common Patterns
|
||||||
|
|
||||||
|
#### Transcoding to File
|
||||||
|
|
||||||
|
```bash
|
||||||
|
barn run --tag=transcode -- ffmpeg -y -progress pipe:1 -threads 0 -i input.mkv -c:v libx264 -crf 23 output.mp4
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Hardware-Accelerated Encoding (macOS)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
barn run --tag=transcode -- ffmpeg -y -progress pipe:1 -threads 0 -i input.mkv -c:v h264_videotoolbox -b:v 4M output.mp4
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Analyzing Media with ffprobe
|
||||||
|
|
||||||
|
```bash
|
||||||
|
barn run --tag=analyze -- ffprobe -v quiet -print_format json -show_format -show_streams input.mp4
|
||||||
|
```
|
||||||
|
- stdout: JSON output (when using `-print_format json`)
|
||||||
|
- stderr: errors only (when using `-v quiet`)
|
||||||
|
|
||||||
|
## Output Streams (stdout vs stderr)
|
||||||
|
|
||||||
|
By default (without `-progress pipe:1`), FFmpeg outputs progress to **stderr**, not stdout. This is by design to allow piping video data through stdout:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# FFmpeg can pipe video to another command via stdout
|
||||||
|
ffmpeg -i input.mp4 -f mp4 - | another_command
|
||||||
|
```
|
||||||
|
|
||||||
|
Without `-progress pipe:1`:
|
||||||
|
- `stdout.log`: Empty (video goes to output file)
|
||||||
|
- `stderr.log`: All FFmpeg output (version info, progress, statistics)
|
||||||
|
|
||||||
|
This is correct behavior, not a bug. Use `-progress pipe:1` to get progress in stdout.
|
||||||
|
|
||||||
|
## Monitoring FFmpeg Jobs
|
||||||
|
|
||||||
|
To check FFmpeg progress:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Get current progress (human-readable)
|
||||||
|
barn describe <job-id> --logs
|
||||||
|
|
||||||
|
# Get current progress (JSON for parsing)
|
||||||
|
barn describe <job-id> --logs --output=json
|
||||||
|
```
|
||||||
|
|
||||||
|
The `logs.stdout` field contains the `-progress pipe:1` output with fields like `frame=`, `fps=`, `speed=`, and `progress=`.
|
||||||
|
|
||||||
|
## FFmpeg Exit Codes
|
||||||
|
|
||||||
|
| Exit Code | Meaning |
|
||||||
|
|-----------|---------|
|
||||||
|
| 0 | Success |
|
||||||
|
| 1 | Generic error (check stderr for details) |
|
||||||
|
| 69 | Invalid data in input |
|
||||||
|
| 183 | Output file already exists (use `-y` to overwrite) |
|
||||||
|
|
||||||
|
## Suppressing FFmpeg Output
|
||||||
|
|
||||||
|
If you want minimal output:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ffmpeg -y -progress pipe:1 -loglevel error -i input.mp4 output.mp4
|
||||||
|
```
|
||||||
|
|
||||||
|
Or for completely silent operation (progress only, no errors):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ffmpeg -y -progress pipe:1 -loglevel quiet -i input.mp4 output.mp4
|
||||||
|
```
|
||||||
|
|
||||||
|
Note: Even with `-loglevel quiet`, fatal errors still go to stderr.
|
||||||
@@ -78,6 +78,7 @@ Example:
|
|||||||
manifest.json
|
manifest.json
|
||||||
state
|
state
|
||||||
stage
|
stage
|
||||||
|
load_level
|
||||||
pid
|
pid
|
||||||
heartbeat
|
heartbeat
|
||||||
exit_code
|
exit_code
|
||||||
@@ -121,6 +122,7 @@ Written once at job creation.
|
|||||||
|---------------|--------------------------------------------------------|
|
|---------------|--------------------------------------------------------|
|
||||||
| `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` |
|
| `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` |
|
||||||
| `tag` | user defined string |
|
| `tag` | user defined string |
|
||||||
|
| `load_level` | `HIGH`, `MEDIUM`, or `LOW` (for scheduling priority) |
|
||||||
| `created_at` | Job creation timestamp |
|
| `created_at` | Job creation timestamp |
|
||||||
| `started_at` | Execution start timestamp |
|
| `started_at` | Execution start timestamp |
|
||||||
| `finished_at` | Execution end timestamp |
|
| `finished_at` | Execution end timestamp |
|
||||||
@@ -280,6 +282,7 @@ Contains daemon-level events, not job output.
|
|||||||
manifest.json
|
manifest.json
|
||||||
state → running
|
state → running
|
||||||
stage → transcode
|
stage → transcode
|
||||||
|
load_level → HIGH
|
||||||
pid → 12345
|
pid → 12345
|
||||||
heartbeat → 2026-01-21T18:42:10Z
|
heartbeat → 2026-01-21T18:42:10Z
|
||||||
started_at → 2026-01-21T18:40:01Z
|
started_at → 2026-01-21T18:40:01Z
|
||||||
|
|||||||
@@ -503,6 +503,7 @@ retry_delay_seconds = 5
|
|||||||
|
|
||||||
**Expected:**
|
**Expected:**
|
||||||
- Job retries automatically
|
- Job retries automatically
|
||||||
|
- `barn status` shows retry count in **RETRIES** column and next retry time in **NEXT RETRY** column
|
||||||
- Eventually succeeds on 3rd attempt
|
- Eventually succeeds on 3rd attempt
|
||||||
- retry_count file shows retry history
|
- retry_count file shows retry history
|
||||||
|
|
||||||
@@ -523,7 +524,8 @@ retry_delay_seconds = 5
|
|||||||
|
|
||||||
**Expected:**
|
**Expected:**
|
||||||
- Job state is "failed"
|
- Job state is "failed"
|
||||||
- retry_count equals max_retries
|
- **RETRIES** column shows retry count equal to max_retries
|
||||||
|
- **NEXT RETRY** column shows `-` (no further retries)
|
||||||
- No more retry attempts
|
- No more retry attempts
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -538,7 +540,7 @@ barn status
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Expected:**
|
**Expected:**
|
||||||
- Formatted table or list
|
- Formatted table with columns: ID, STATE, LOAD, TAG, CREATED, EXIT, PID, RETRIES, NEXT RETRY
|
||||||
- Human-readable timestamps
|
- Human-readable timestamps
|
||||||
- Clear column headers
|
- Clear column headers
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
|
|
||||||
<groupId>com.samsonmedia</groupId>
|
<groupId>com.samsonmedia</groupId>
|
||||||
<artifactId>barn</artifactId>
|
<artifactId>barn</artifactId>
|
||||||
<version>0.1.5</version>
|
<version>0.3.0</version>
|
||||||
<packaging>jar</packaging>
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
<name>Barn</name>
|
<name>Barn</name>
|
||||||
@@ -121,6 +121,22 @@
|
|||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
<resources>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>true</filtering>
|
||||||
|
<includes>
|
||||||
|
<include>version.properties</include>
|
||||||
|
</includes>
|
||||||
|
</resource>
|
||||||
|
<resource>
|
||||||
|
<directory>src/main/resources</directory>
|
||||||
|
<filtering>false</filtering>
|
||||||
|
<excludes>
|
||||||
|
<exclude>version.properties</exclude>
|
||||||
|
</excludes>
|
||||||
|
</resource>
|
||||||
|
</resources>
|
||||||
<plugins>
|
<plugins>
|
||||||
<!-- Compiler -->
|
<!-- Compiler -->
|
||||||
<plugin>
|
<plugin>
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import picocli.CommandLine.Spec;
|
|||||||
@Command(
|
@Command(
|
||||||
name = "barn",
|
name = "barn",
|
||||||
mixinStandardHelpOptions = true,
|
mixinStandardHelpOptions = true,
|
||||||
version = "barn 0.1.2",
|
versionProvider = VersionProvider.class,
|
||||||
description = "Cross-platform job daemon for media processing",
|
description = "Cross-platform job daemon for media processing",
|
||||||
subcommands = {
|
subcommands = {
|
||||||
RunCommand.class,
|
RunCommand.class,
|
||||||
|
|||||||
@@ -16,7 +16,8 @@ import picocli.CommandLine.Spec;
|
|||||||
subcommands = {
|
subcommands = {
|
||||||
ConfigShowCommand.class,
|
ConfigShowCommand.class,
|
||||||
ConfigValidateCommand.class,
|
ConfigValidateCommand.class,
|
||||||
ConfigInitCommand.class
|
ConfigInitCommand.class,
|
||||||
|
ConfigInstallCommand.class
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
public class ConfigCommand implements Runnable {
|
public class ConfigCommand implements Runnable {
|
||||||
|
|||||||
@@ -37,7 +37,7 @@ public class ConfigInitCommand extends BaseCommand {
|
|||||||
: ConfigDefaults.getUserConfigPath();
|
: ConfigDefaults.getUserConfigPath();
|
||||||
|
|
||||||
if (Files.exists(targetPath) && !force) {
|
if (Files.exists(targetPath) && !force) {
|
||||||
outputError("Configuration file already exists: " + targetPath);
|
outputError("Configuration file already exists: \"" + targetPath + "\"");
|
||||||
outputError("Use --force to overwrite");
|
outputError("Use --force to overwrite");
|
||||||
return EXIT_ERROR;
|
return EXIT_ERROR;
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,7 @@ public class ConfigInitCommand extends BaseCommand {
|
|||||||
String content = generateDefaultConfig();
|
String content = generateDefaultConfig();
|
||||||
Files.writeString(targetPath, content);
|
Files.writeString(targetPath, content);
|
||||||
|
|
||||||
getOut().println("Configuration file created: " + targetPath);
|
getOut().println("Configuration file created: \"" + targetPath + "\"");
|
||||||
return EXIT_SUCCESS;
|
return EXIT_SUCCESS;
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package com.samsonmedia.barn.cli;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||||
|
|
||||||
|
import picocli.CommandLine.Command;
|
||||||
|
import picocli.CommandLine.Option;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Command to install default configuration files.
|
||||||
|
*
|
||||||
|
* <p>Installs barn.conf and load level whitelist files (high.load, medium.load, low.load)
|
||||||
|
* to the specified directory. By default, installs to the system config directory.
|
||||||
|
*/
|
||||||
|
@Command(
|
||||||
|
name = "install",
|
||||||
|
mixinStandardHelpOptions = true,
|
||||||
|
description = "Install default configuration files"
|
||||||
|
)
|
||||||
|
public class ConfigInstallCommand extends BaseCommand {
|
||||||
|
|
||||||
|
private static final String DEFAULTS_PATH = "/defaults/";
|
||||||
|
private static final List<String> CONFIG_FILES = List.of(
|
||||||
|
"barn.conf",
|
||||||
|
"high.load",
|
||||||
|
"medium.load",
|
||||||
|
"low.load"
|
||||||
|
);
|
||||||
|
|
||||||
|
@Option(names = {"--directory", "-d"}, description = "Target directory for config files")
|
||||||
|
private Path targetDirectory;
|
||||||
|
|
||||||
|
@Option(names = {"--force", "-f"}, description = "Skip confirmation and overwrite existing files")
|
||||||
|
private boolean force;
|
||||||
|
|
||||||
|
@Option(names = {"--show"}, description = "Show what would be installed without writing")
|
||||||
|
private boolean showOnly;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Integer call() {
|
||||||
|
Path targetDir = targetDirectory != null
|
||||||
|
? targetDirectory
|
||||||
|
: ConfigDefaults.getSystemConfigDir();
|
||||||
|
|
||||||
|
if (showOnly) {
|
||||||
|
return showWhatWouldBeInstalled(targetDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!force) {
|
||||||
|
getOut().println("The following files will be created/overwritten:");
|
||||||
|
for (String file : CONFIG_FILES) {
|
||||||
|
getOut().println(" " + targetDir.resolve(file));
|
||||||
|
}
|
||||||
|
getOut().println();
|
||||||
|
getOut().println("WARNING: This will overwrite any existing configuration.");
|
||||||
|
getOut().println("Use --force to proceed, or --show to preview without writing.");
|
||||||
|
return EXIT_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
return installConfigFiles(targetDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Integer showWhatWouldBeInstalled(Path targetDir) {
|
||||||
|
getOut().println("Files that would be installed to: " + targetDir);
|
||||||
|
getOut().println();
|
||||||
|
|
||||||
|
for (String filename : CONFIG_FILES) {
|
||||||
|
getOut().println("=== " + filename + " ===");
|
||||||
|
try {
|
||||||
|
String content = loadResourceFile(filename);
|
||||||
|
getOut().println(content);
|
||||||
|
getOut().println();
|
||||||
|
} catch (IOException e) {
|
||||||
|
outputError("Failed to read resource: " + filename + " - " + e.getMessage());
|
||||||
|
return EXIT_ERROR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return EXIT_SUCCESS;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Integer installConfigFiles(Path targetDir) {
|
||||||
|
try {
|
||||||
|
// Create target directory if needed
|
||||||
|
if (!Files.exists(targetDir)) {
|
||||||
|
Files.createDirectories(targetDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (String filename : CONFIG_FILES) {
|
||||||
|
Path targetPath = targetDir.resolve(filename);
|
||||||
|
String content = loadResourceFile(filename);
|
||||||
|
Files.writeString(targetPath, content);
|
||||||
|
getOut().println("Installed: " + targetPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
getOut().println();
|
||||||
|
getOut().println("Configuration installed successfully.");
|
||||||
|
getOut().println("Config directory: " + targetDir);
|
||||||
|
|
||||||
|
return EXIT_SUCCESS;
|
||||||
|
|
||||||
|
} catch (IOException e) {
|
||||||
|
outputError("Failed to install configuration: " + e.getMessage());
|
||||||
|
return EXIT_ERROR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String loadResourceFile(String filename) throws IOException {
|
||||||
|
String resourcePath = DEFAULTS_PATH + filename;
|
||||||
|
try (InputStream is = ConfigInstallCommand.class.getResourceAsStream(resourcePath)) {
|
||||||
|
if (is == null) {
|
||||||
|
throw new IOException("Resource not found: " + resourcePath);
|
||||||
|
}
|
||||||
|
return new String(is.readAllBytes(), StandardCharsets.UTF_8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -121,6 +121,13 @@ public class ConfigShowCommand extends BaseCommand {
|
|||||||
sb.append(String.format("base_dir = %s%n", config.storage().baseDir()));
|
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("max_disk_usage_gb = %d%n", config.storage().maxDiskUsageGb()));
|
||||||
sb.append(String.format("preserve_work_dir = %b%n", config.storage().preserveWorkDir()));
|
sb.append(String.format("preserve_work_dir = %b%n", config.storage().preserveWorkDir()));
|
||||||
|
sb.append("\n");
|
||||||
|
|
||||||
|
// Load section
|
||||||
|
sb.append("[load]\n");
|
||||||
|
sb.append(String.format("max_high_jobs = %d%n", config.loadLevels().maxHighJobs()));
|
||||||
|
sb.append(String.format("max_medium_jobs = %d%n", config.loadLevels().maxMediumJobs()));
|
||||||
|
sb.append(String.format("max_low_jobs = %d%n", config.loadLevels().maxLowJobs()));
|
||||||
|
|
||||||
getOut().println(sb.toString().trim());
|
getOut().println(sb.toString().trim());
|
||||||
}
|
}
|
||||||
@@ -131,6 +138,7 @@ public class ConfigShowCommand extends BaseCommand {
|
|||||||
map.put("jobs", buildJobsSection(config));
|
map.put("jobs", buildJobsSection(config));
|
||||||
map.put("cleanup", buildCleanupSection(config));
|
map.put("cleanup", buildCleanupSection(config));
|
||||||
map.put("storage", buildStorageSection(config));
|
map.put("storage", buildStorageSection(config));
|
||||||
|
map.put("load", buildLoadSection(config));
|
||||||
return map;
|
return map;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -171,4 +179,12 @@ public class ConfigShowCommand extends BaseCommand {
|
|||||||
storage.put("preserve_work_dir", config.storage().preserveWorkDir());
|
storage.put("preserve_work_dir", config.storage().preserveWorkDir());
|
||||||
return storage;
|
return storage;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private Map<String, Object> buildLoadSection(Config config) {
|
||||||
|
Map<String, Object> load = new LinkedHashMap<>();
|
||||||
|
load.put("max_high_jobs", config.loadLevels().maxHighJobs());
|
||||||
|
load.put("max_medium_jobs", config.loadLevels().maxMediumJobs());
|
||||||
|
load.put("max_low_jobs", config.loadLevels().maxLowJobs());
|
||||||
|
return load;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -102,6 +102,7 @@ public class HumanFormatter implements OutputFormatter {
|
|||||||
StringBuilder sb = new StringBuilder();
|
StringBuilder sb = new StringBuilder();
|
||||||
sb.append(colorize("Job: ", BOLD)).append(job.id()).append("\n");
|
sb.append(colorize("Job: ", BOLD)).append(job.id()).append("\n");
|
||||||
sb.append(" State: ").append(colorizeState(job.state())).append("\n");
|
sb.append(" State: ").append(colorizeState(job.state())).append("\n");
|
||||||
|
sb.append(" Load: ").append(job.loadLevel().toString().toLowerCase(Locale.ROOT)).append("\n");
|
||||||
sb.append(" Command: ").append(String.join(" ", job.command())).append("\n");
|
sb.append(" Command: ").append(String.join(" ", job.command())).append("\n");
|
||||||
|
|
||||||
if (job.tag() != null) {
|
if (job.tag() != null) {
|
||||||
@@ -134,12 +135,17 @@ public class HumanFormatter implements OutputFormatter {
|
|||||||
sb.append(" Retries: ").append(job.retryCount()).append("\n");
|
sb.append(" Retries: ").append(job.retryCount()).append("\n");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (job.retryAt() != null) {
|
||||||
|
sb.append(" Retry At: ").append(formatTimestamp(job.retryAt())).append("\n");
|
||||||
|
}
|
||||||
|
|
||||||
return sb.toString().trim();
|
return sb.toString().trim();
|
||||||
}
|
}
|
||||||
|
|
||||||
private String formatJobTable(List<Job> jobs) {
|
private String formatJobTable(List<Job> jobs) {
|
||||||
// Define columns
|
// Define columns
|
||||||
List<String> headers = List.of("ID", "STATE", "TAG", "CREATED", "EXIT");
|
List<String> headers = List.of(
|
||||||
|
"ID", "STATE", "LOAD", "TAG", "CREATED", "EXIT", "RETRIES", "NEXT RETRY");
|
||||||
|
|
||||||
// Convert jobs to rows
|
// Convert jobs to rows
|
||||||
List<List<String>> rows = new ArrayList<>();
|
List<List<String>> rows = new ArrayList<>();
|
||||||
@@ -147,9 +153,12 @@ public class HumanFormatter implements OutputFormatter {
|
|||||||
rows.add(List.of(
|
rows.add(List.of(
|
||||||
job.id(),
|
job.id(),
|
||||||
job.state().toString().toLowerCase(Locale.ROOT),
|
job.state().toString().toLowerCase(Locale.ROOT),
|
||||||
|
job.loadLevel().toString().toLowerCase(Locale.ROOT),
|
||||||
job.tag() != null ? job.tag() : "-",
|
job.tag() != null ? job.tag() : "-",
|
||||||
formatTimestamp(job.createdAt()),
|
formatTimestamp(job.createdAt()),
|
||||||
job.exitCode() != null ? job.exitCode().toString() : "-"
|
job.exitCode() != null ? job.exitCode().toString() : "-",
|
||||||
|
job.retryCount() > 0 ? String.valueOf(job.retryCount()) : "-",
|
||||||
|
job.retryAt() != null ? formatTimestamp(job.retryAt()) : "-"
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -190,7 +199,7 @@ public class HumanFormatter implements OutputFormatter {
|
|||||||
// Apply colors based on column
|
// Apply colors based on column
|
||||||
if (i == 1) { // STATE column
|
if (i == 1) { // STATE column
|
||||||
cell = colorizeState(job.state(), cell);
|
cell = colorizeState(job.state(), cell);
|
||||||
} else if (i == 4 && !cell.trim().equals("-")) { // EXIT column
|
} else if (i == 5 && !cell.trim().equals("-")) { // EXIT column
|
||||||
cell = colorizeExitCode(job.exitCode(), cell);
|
cell = colorizeExitCode(job.exitCode(), cell);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -16,6 +16,8 @@ import com.samsonmedia.barn.ipc.IpcClient;
|
|||||||
import com.samsonmedia.barn.ipc.IpcException;
|
import com.samsonmedia.barn.ipc.IpcException;
|
||||||
import com.samsonmedia.barn.jobs.Job;
|
import com.samsonmedia.barn.jobs.Job;
|
||||||
import com.samsonmedia.barn.jobs.JobRepository;
|
import com.samsonmedia.barn.jobs.JobRepository;
|
||||||
|
import com.samsonmedia.barn.jobs.LoadLevel;
|
||||||
|
import com.samsonmedia.barn.jobs.LoadLevelClassifier;
|
||||||
import com.samsonmedia.barn.logging.BarnLogger;
|
import com.samsonmedia.barn.logging.BarnLogger;
|
||||||
import com.samsonmedia.barn.state.BarnDirectories;
|
import com.samsonmedia.barn.state.BarnDirectories;
|
||||||
|
|
||||||
@@ -41,6 +43,10 @@ public class RunCommand extends BaseCommand {
|
|||||||
@Option(names = {"--tag", "-t"}, description = "Tag for filtering jobs")
|
@Option(names = {"--tag", "-t"}, description = "Tag for filtering jobs")
|
||||||
private String tag;
|
private String tag;
|
||||||
|
|
||||||
|
@Option(names = {"--load-level", "-l"},
|
||||||
|
description = "Load level classification: ${COMPLETION-CANDIDATES} (default: auto-detect)")
|
||||||
|
private LoadLevel loadLevel;
|
||||||
|
|
||||||
@Option(names = {"--max-retries"}, description = "Override max retries")
|
@Option(names = {"--max-retries"}, description = "Override max retries")
|
||||||
private Integer maxRetries;
|
private Integer maxRetries;
|
||||||
|
|
||||||
@@ -87,10 +93,19 @@ public class RunCommand extends BaseCommand {
|
|||||||
JobRepository repository = new JobRepository(dirs);
|
JobRepository repository = new JobRepository(dirs);
|
||||||
JobsConfig jobsConfig = buildJobsConfig();
|
JobsConfig jobsConfig = buildJobsConfig();
|
||||||
|
|
||||||
// Create the job
|
// Determine load level: use explicit override, or auto-classify from whitelists
|
||||||
Job job = repository.create(command, tag, jobsConfig);
|
LoadLevel level;
|
||||||
|
if (loadLevel != null) {
|
||||||
|
level = loadLevel;
|
||||||
|
} else {
|
||||||
|
level = LoadLevelClassifier.loadFromConfigDir().classify(command);
|
||||||
|
LOG.debug("Auto-classified command as load level: {}", level);
|
||||||
|
}
|
||||||
|
|
||||||
LOG.info("Created job {} in offline mode", job.id());
|
// Create the job
|
||||||
|
Job job = repository.create(command, tag, jobsConfig, level);
|
||||||
|
|
||||||
|
LOG.info("Created job {} in offline mode with load level {}", job.id(), level);
|
||||||
|
|
||||||
// Output job info in the appropriate format
|
// Output job info in the appropriate format
|
||||||
outputJobCreated(job);
|
outputJobCreated(job);
|
||||||
@@ -111,6 +126,9 @@ public class RunCommand extends BaseCommand {
|
|||||||
if (tag != null) {
|
if (tag != null) {
|
||||||
payload.put("tag", tag);
|
payload.put("tag", tag);
|
||||||
}
|
}
|
||||||
|
if (loadLevel != null) {
|
||||||
|
payload.put("loadLevel", loadLevel.name());
|
||||||
|
}
|
||||||
if (maxRetries != null) {
|
if (maxRetries != null) {
|
||||||
payload.put("maxRetries", maxRetries);
|
payload.put("maxRetries", maxRetries);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,10 +19,12 @@ import picocli.CommandLine.Option;
|
|||||||
*
|
*
|
||||||
* <p>Supports platform-specific service installation:
|
* <p>Supports platform-specific service installation:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>macOS: launchd (LaunchDaemons/LaunchAgents)</li>
|
* <li>macOS: launchd (LaunchDaemons)</li>
|
||||||
* <li>Linux: systemd (planned)</li>
|
* <li>Linux: systemd</li>
|
||||||
* <li>Windows: Windows Service (planned)</li>
|
* <li>Windows: Windows Service</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
|
*
|
||||||
|
* <p>System-wide installation requires root/administrator privileges.
|
||||||
*/
|
*/
|
||||||
@Command(
|
@Command(
|
||||||
name = "install",
|
name = "install",
|
||||||
@@ -33,9 +35,6 @@ public class ServiceInstallCommand extends BaseCommand {
|
|||||||
|
|
||||||
private static final BarnLogger LOG = BarnLogger.getLogger(ServiceInstallCommand.class);
|
private static final BarnLogger LOG = BarnLogger.getLogger(ServiceInstallCommand.class);
|
||||||
|
|
||||||
@Option(names = {"--user"}, description = "Install as user service instead of system-wide")
|
|
||||||
private boolean userService;
|
|
||||||
|
|
||||||
@Option(names = {"--barn-dir"}, description = "Barn data directory")
|
@Option(names = {"--barn-dir"}, description = "Barn data directory")
|
||||||
private Path barnDir;
|
private Path barnDir;
|
||||||
|
|
||||||
@@ -72,12 +71,11 @@ public class ServiceInstallCommand extends BaseCommand {
|
|||||||
|
|
||||||
// Generate and write plist
|
// Generate and write plist
|
||||||
String plistContent = launchd.generatePlist(effectiveBinaryPath, effectiveBarnDir);
|
String plistContent = launchd.generatePlist(effectiveBinaryPath, effectiveBarnDir);
|
||||||
Path plistPath = userService ? launchd.getUserAgentPath() : launchd.getSystemDaemonPath();
|
Path plistPath = launchd.getSystemDaemonPath();
|
||||||
|
|
||||||
// Check if we need sudo for system-wide installation
|
// Check if we need sudo for system-wide installation
|
||||||
if (!userService && !canWriteToPath(plistPath.getParent())) {
|
if (!canWriteToPath(plistPath.getParent())) {
|
||||||
outputError("System-wide installation requires root privileges. "
|
outputError("System-wide installation requires root privileges. Run with sudo.");
|
||||||
+ "Run with sudo or use --user for user-level installation.");
|
|
||||||
return EXIT_ERROR;
|
return EXIT_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,10 +84,9 @@ public class ServiceInstallCommand extends BaseCommand {
|
|||||||
// Load the service
|
// Load the service
|
||||||
launchd.load(plistPath);
|
launchd.load(plistPath);
|
||||||
|
|
||||||
String serviceType = userService ? "user agent" : "system daemon";
|
getOut().println("Barn installed as macOS system daemon");
|
||||||
getOut().println("Barn installed as macOS " + serviceType);
|
|
||||||
getOut().println("Plist location: " + plistPath);
|
getOut().println("Plist location: " + plistPath);
|
||||||
getOut().println("Service will start automatically on login/boot.");
|
getOut().println("Service will start automatically on boot.");
|
||||||
getOut().println();
|
getOut().println();
|
||||||
getOut().println("To start now: barn service start");
|
getOut().println("To start now: barn service start");
|
||||||
getOut().println("To uninstall: barn service uninstall");
|
getOut().println("To uninstall: barn service uninstall");
|
||||||
@@ -114,7 +111,7 @@ public class ServiceInstallCommand extends BaseCommand {
|
|||||||
SystemdManager systemd = new SystemdManager();
|
SystemdManager systemd = new SystemdManager();
|
||||||
|
|
||||||
// Check if already installed
|
// Check if already installed
|
||||||
Path unitPath = userService ? systemd.getUserServicePath() : systemd.getSystemServicePath();
|
Path unitPath = systemd.getSystemServicePath();
|
||||||
if (Files.exists(unitPath)) {
|
if (Files.exists(unitPath)) {
|
||||||
outputError("Barn service is already installed. Use 'barn service uninstall' first.");
|
outputError("Barn service is already installed. Use 'barn service uninstall' first.");
|
||||||
return EXIT_ERROR;
|
return EXIT_ERROR;
|
||||||
@@ -128,24 +125,22 @@ public class ServiceInstallCommand extends BaseCommand {
|
|||||||
Files.createDirectories(effectiveBarnDir);
|
Files.createDirectories(effectiveBarnDir);
|
||||||
Files.createDirectories(effectiveBarnDir.resolve("logs"));
|
Files.createDirectories(effectiveBarnDir.resolve("logs"));
|
||||||
|
|
||||||
// Generate and write unit file
|
// Generate and write unit file (system-wide, not user)
|
||||||
String unitContent = systemd.generateUnitFile(effectiveBinaryPath, effectiveBarnDir, userService);
|
String unitContent = systemd.generateUnitFile(effectiveBinaryPath, effectiveBarnDir, false);
|
||||||
|
|
||||||
// Check if we need sudo for system-wide installation
|
// Check if we need sudo for system-wide installation
|
||||||
if (!userService && !canWriteToPath(unitPath.getParent())) {
|
if (!canWriteToPath(unitPath.getParent())) {
|
||||||
outputError("System-wide installation requires root privileges. "
|
outputError("System-wide installation requires root privileges. Run with sudo.");
|
||||||
+ "Run with sudo or use --user for user-level installation.");
|
|
||||||
return EXIT_ERROR;
|
return EXIT_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
systemd.writeUnitFile(unitPath, unitContent);
|
systemd.writeUnitFile(unitPath, unitContent);
|
||||||
|
|
||||||
// Reload systemd and enable the service
|
// Reload systemd and enable the service (system-wide)
|
||||||
systemd.daemonReload(userService);
|
systemd.daemonReload(false);
|
||||||
systemd.enable(userService);
|
systemd.enable(false);
|
||||||
|
|
||||||
String serviceType = userService ? "user service" : "system service";
|
getOut().println("Barn installed as Linux system service");
|
||||||
getOut().println("Barn installed as Linux " + serviceType);
|
|
||||||
getOut().println("Unit file: " + unitPath);
|
getOut().println("Unit file: " + unitPath);
|
||||||
getOut().println("Service will start automatically on boot.");
|
getOut().println("Service will start automatically on boot.");
|
||||||
getOut().println();
|
getOut().println();
|
||||||
|
|||||||
@@ -18,9 +18,11 @@ import picocli.CommandLine.Option;
|
|||||||
* <p>Removes platform-specific service registration:
|
* <p>Removes platform-specific service registration:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>macOS: launchd plist files</li>
|
* <li>macOS: launchd plist files</li>
|
||||||
* <li>Linux: systemd unit files (planned)</li>
|
* <li>Linux: systemd unit files</li>
|
||||||
* <li>Windows: Windows Service registration (planned)</li>
|
* <li>Windows: Windows Service registration</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
|
*
|
||||||
|
* <p>System-wide uninstallation requires root/administrator privileges.
|
||||||
*/
|
*/
|
||||||
@Command(
|
@Command(
|
||||||
name = "uninstall",
|
name = "uninstall",
|
||||||
@@ -31,9 +33,6 @@ public class ServiceUninstallCommand extends BaseCommand {
|
|||||||
|
|
||||||
private static final BarnLogger LOG = BarnLogger.getLogger(ServiceUninstallCommand.class);
|
private static final BarnLogger LOG = BarnLogger.getLogger(ServiceUninstallCommand.class);
|
||||||
|
|
||||||
@Option(names = {"--user"}, description = "Uninstall user service instead of system-wide")
|
|
||||||
private boolean userService;
|
|
||||||
|
|
||||||
@Option(names = {"--force"}, description = "Force uninstall even if service is running")
|
@Option(names = {"--force"}, description = "Force uninstall even if service is running")
|
||||||
private boolean force;
|
private boolean force;
|
||||||
|
|
||||||
@@ -51,27 +50,17 @@ public class ServiceUninstallCommand extends BaseCommand {
|
|||||||
private int uninstallMacOs() {
|
private int uninstallMacOs() {
|
||||||
LaunchdManager launchd = new LaunchdManager();
|
LaunchdManager launchd = new LaunchdManager();
|
||||||
|
|
||||||
Path plistPath = userService ? launchd.getUserAgentPath() : launchd.getSystemDaemonPath();
|
Path plistPath = launchd.getSystemDaemonPath();
|
||||||
|
|
||||||
// Check if installed
|
// Check if installed
|
||||||
if (!Files.exists(plistPath)) {
|
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");
|
outputError("Barn service is not installed");
|
||||||
return EXIT_ERROR;
|
return EXIT_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if we need sudo for system-wide uninstallation
|
// Check if we need sudo for system-wide uninstallation
|
||||||
if (!userService && !canWriteToPath(plistPath)) {
|
if (!canWriteToPath(plistPath)) {
|
||||||
outputError("System-wide uninstallation requires root privileges. "
|
outputError("System-wide uninstallation requires root privileges. Run with sudo.");
|
||||||
+ "Run with sudo or use --user for user-level service.");
|
|
||||||
return EXIT_ERROR;
|
return EXIT_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -98,8 +87,7 @@ public class ServiceUninstallCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
String serviceType = userService ? "user agent" : "system daemon";
|
getOut().println("Barn system daemon uninstalled successfully");
|
||||||
getOut().println("Barn " + serviceType + " uninstalled successfully");
|
|
||||||
getOut().println("Removed: " + plistPath);
|
getOut().println("Removed: " + plistPath);
|
||||||
|
|
||||||
return EXIT_SUCCESS;
|
return EXIT_SUCCESS;
|
||||||
@@ -117,35 +105,25 @@ public class ServiceUninstallCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
SystemdManager systemd = new SystemdManager();
|
SystemdManager systemd = new SystemdManager();
|
||||||
Path unitPath = userService ? systemd.getUserServicePath() : systemd.getSystemServicePath();
|
Path unitPath = systemd.getSystemServicePath();
|
||||||
|
|
||||||
// Check if installed
|
// Check if installed
|
||||||
if (!Files.exists(unitPath)) {
|
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");
|
outputError("Barn service is not installed");
|
||||||
return EXIT_ERROR;
|
return EXIT_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if we need sudo for system-wide uninstallation
|
// Check if we need sudo for system-wide uninstallation
|
||||||
if (!userService && !canWriteToPath(unitPath)) {
|
if (!canWriteToPath(unitPath)) {
|
||||||
outputError("System-wide uninstallation requires root privileges. "
|
outputError("System-wide uninstallation requires root privileges. Run with sudo.");
|
||||||
+ "Run with sudo or use --user for user-level service.");
|
|
||||||
return EXIT_ERROR;
|
return EXIT_ERROR;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Stop and disable the service first
|
// Stop and disable the service first (system-wide)
|
||||||
if (systemd.isActive(userService)) {
|
if (systemd.isActive(false)) {
|
||||||
try {
|
try {
|
||||||
systemd.stop(userService);
|
systemd.stop(false);
|
||||||
} catch (SystemdManager.SystemdException e) {
|
} catch (SystemdManager.SystemdException e) {
|
||||||
if (!force) {
|
if (!force) {
|
||||||
outputError("Failed to stop service: " + e.getMessage()
|
outputError("Failed to stop service: " + e.getMessage()
|
||||||
@@ -156,9 +134,9 @@ public class ServiceUninstallCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (systemd.isEnabled(userService)) {
|
if (systemd.isEnabled(false)) {
|
||||||
try {
|
try {
|
||||||
systemd.disable(userService);
|
systemd.disable(false);
|
||||||
} catch (SystemdManager.SystemdException e) {
|
} catch (SystemdManager.SystemdException e) {
|
||||||
LOG.warn("Failed to disable service: {}", e.getMessage());
|
LOG.warn("Failed to disable service: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
@@ -172,15 +150,14 @@ public class ServiceUninstallCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reload systemd
|
// Reload systemd (system-wide)
|
||||||
try {
|
try {
|
||||||
systemd.daemonReload(userService);
|
systemd.daemonReload(false);
|
||||||
} catch (SystemdManager.SystemdException e) {
|
} catch (SystemdManager.SystemdException e) {
|
||||||
LOG.warn("Failed to reload systemd: {}", e.getMessage());
|
LOG.warn("Failed to reload systemd: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
String serviceType = userService ? "user service" : "system service";
|
getOut().println("Barn system service uninstalled successfully");
|
||||||
getOut().println("Barn " + serviceType + " uninstalled successfully");
|
|
||||||
getOut().println("Removed: " + unitPath);
|
getOut().println("Removed: " + unitPath);
|
||||||
|
|
||||||
return EXIT_SUCCESS;
|
return EXIT_SUCCESS;
|
||||||
|
|||||||
@@ -195,18 +195,23 @@ public class StatusCommand extends BaseCommand {
|
|||||||
.max().orElse(3));
|
.max().orElse(3));
|
||||||
|
|
||||||
// Header
|
// Header
|
||||||
sb.append(String.format("%-" + idWidth + "s %-9s %-" + tagWidth + "s %-19s %-4s %-8s%n",
|
sb.append(String.format(
|
||||||
"ID", "STATE", "TAG", "CREATED", "EXIT", "PID"));
|
"%-" + idWidth + "s %-9s %-6s %-" + tagWidth + "s %-19s %-4s %-8s %-7s %-19s%n",
|
||||||
|
"ID", "STATE", "LOAD", "TAG", "CREATED", "EXIT", "PID", "RETRIES", "NEXT RETRY"));
|
||||||
|
|
||||||
// Rows
|
// Rows
|
||||||
for (Job job : jobs) {
|
for (Job job : jobs) {
|
||||||
sb.append(String.format("%-" + idWidth + "s %-9s %-" + tagWidth + "s %-19s %-4s %-8s%n",
|
sb.append(String.format(
|
||||||
|
"%-" + idWidth + "s %-9s %-6s %-" + tagWidth + "s %-19s %-4s %-8s %-7s %-19s%n",
|
||||||
job.id(),
|
job.id(),
|
||||||
job.state().toString().toLowerCase(Locale.ROOT),
|
job.state().toString().toLowerCase(Locale.ROOT),
|
||||||
|
job.loadLevel().toString().toLowerCase(Locale.ROOT),
|
||||||
job.tag() != null ? job.tag() : "-",
|
job.tag() != null ? job.tag() : "-",
|
||||||
formatTimestamp(job.createdAt()),
|
formatTimestamp(job.createdAt()),
|
||||||
job.exitCode() != null ? job.exitCode().toString() : "-",
|
job.exitCode() != null ? job.exitCode().toString() : "-",
|
||||||
job.pid() != null ? job.pid().toString() : "-"));
|
job.pid() != null ? job.pid().toString() : "-",
|
||||||
|
job.retryCount() > 0 ? String.valueOf(job.retryCount()) : "-",
|
||||||
|
job.retryAt() != null ? formatTimestamp(job.retryAt()) : "-"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Summary
|
// Summary
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
package com.samsonmedia.barn.cli;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.io.InputStream;
|
||||||
|
import java.util.Properties;
|
||||||
|
|
||||||
|
import picocli.CommandLine.IVersionProvider;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Provides version information from the version.properties resource file.
|
||||||
|
*
|
||||||
|
* <p>The version is injected at build time via Maven resource filtering.
|
||||||
|
*/
|
||||||
|
public final class VersionProvider implements IVersionProvider {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String[] getVersion() {
|
||||||
|
String version = "unknown";
|
||||||
|
try (InputStream is = getClass().getResourceAsStream("/version.properties")) {
|
||||||
|
if (is != null) {
|
||||||
|
Properties props = new Properties();
|
||||||
|
props.load(is);
|
||||||
|
version = props.getProperty("version", "unknown");
|
||||||
|
}
|
||||||
|
} catch (IOException e) {
|
||||||
|
// Fall back to unknown
|
||||||
|
}
|
||||||
|
return new String[]{"barn " + version};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
package com.samsonmedia.barn.config;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches commands against load level whitelist entries.
|
||||||
|
*
|
||||||
|
* <p>Commands can be matched by:
|
||||||
|
* <ul>
|
||||||
|
* <li>Executable name only (e.g., "ffmpeg")</li>
|
||||||
|
* <li>Full path to executable (e.g., "/usr/local/bin/ffmpeg")</li>
|
||||||
|
* <li>Directory containing executables (e.g., "/opt/encoders/")</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
public sealed interface CommandMatcher {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if this matcher matches the given command.
|
||||||
|
*
|
||||||
|
* @param command the command and arguments (first element is the executable)
|
||||||
|
* @return true if this matcher matches the command
|
||||||
|
*/
|
||||||
|
boolean matches(List<String> command);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches commands by executable name only.
|
||||||
|
*
|
||||||
|
* <p>The executable name is extracted from the command path and compared.
|
||||||
|
* For example, "ffmpeg" matches both "ffmpeg" and "/usr/bin/ffmpeg".
|
||||||
|
*
|
||||||
|
* @param name the executable name to match (without path)
|
||||||
|
*/
|
||||||
|
record ExecutableName(String name) implements CommandMatcher {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates an ExecutableName matcher with validation.
|
||||||
|
*/
|
||||||
|
public ExecutableName {
|
||||||
|
Objects.requireNonNull(name, "name must not be null");
|
||||||
|
if (name.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("name must not be blank");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(List<String> command) {
|
||||||
|
if (command.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
String executable = command.getFirst();
|
||||||
|
Path fileName = Path.of(executable).getFileName();
|
||||||
|
if (fileName == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return name.equals(fileName.toString());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches commands by exact full path.
|
||||||
|
*
|
||||||
|
* <p>The command must exactly match the specified path.
|
||||||
|
*
|
||||||
|
* @param path the full path to match
|
||||||
|
*/
|
||||||
|
record FullPath(Path path) implements CommandMatcher {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a FullPath matcher with validation.
|
||||||
|
*/
|
||||||
|
public FullPath {
|
||||||
|
Objects.requireNonNull(path, "path must not be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(List<String> command) {
|
||||||
|
if (command.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return Path.of(command.getFirst()).equals(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches commands whose executables are in the specified directory.
|
||||||
|
*
|
||||||
|
* <p>Subdirectories are not matched.
|
||||||
|
*
|
||||||
|
* @param directory the directory containing executables
|
||||||
|
*/
|
||||||
|
record Directory(Path directory) implements CommandMatcher {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a Directory matcher with validation.
|
||||||
|
*/
|
||||||
|
public Directory {
|
||||||
|
Objects.requireNonNull(directory, "directory must not be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean matches(List<String> command) {
|
||||||
|
if (command.isEmpty()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
Path commandPath = Path.of(command.getFirst());
|
||||||
|
Path parent = commandPath.getParent();
|
||||||
|
if (parent == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// Normalize both paths for comparison
|
||||||
|
return parent.normalize().equals(directory.normalize());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,12 +9,14 @@ import java.util.Objects;
|
|||||||
* @param jobs job execution configuration
|
* @param jobs job execution configuration
|
||||||
* @param cleanup automatic cleanup configuration
|
* @param cleanup automatic cleanup configuration
|
||||||
* @param storage storage and filesystem configuration
|
* @param storage storage and filesystem configuration
|
||||||
|
* @param loadLevels per-load-level job limits configuration
|
||||||
*/
|
*/
|
||||||
public record Config(
|
public record Config(
|
||||||
ServiceConfig service,
|
ServiceConfig service,
|
||||||
JobsConfig jobs,
|
JobsConfig jobs,
|
||||||
CleanupConfig cleanup,
|
CleanupConfig cleanup,
|
||||||
StorageConfig storage
|
StorageConfig storage,
|
||||||
|
LoadLevelConfig loadLevels
|
||||||
) {
|
) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -25,6 +27,7 @@ public record Config(
|
|||||||
Objects.requireNonNull(jobs, "jobs must not be null");
|
Objects.requireNonNull(jobs, "jobs must not be null");
|
||||||
Objects.requireNonNull(cleanup, "cleanup must not be null");
|
Objects.requireNonNull(cleanup, "cleanup must not be null");
|
||||||
Objects.requireNonNull(storage, "storage must not be null");
|
Objects.requireNonNull(storage, "storage must not be null");
|
||||||
|
Objects.requireNonNull(loadLevels, "loadLevels must not be null");
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,7 +40,8 @@ public record Config(
|
|||||||
ServiceConfig.withDefaults(),
|
ServiceConfig.withDefaults(),
|
||||||
JobsConfig.withDefaults(),
|
JobsConfig.withDefaults(),
|
||||||
CleanupConfig.withDefaults(),
|
CleanupConfig.withDefaults(),
|
||||||
StorageConfig.withDefaults()
|
StorageConfig.withDefaults(),
|
||||||
|
LoadLevelConfig.withDefaults()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -77,6 +77,44 @@ public final class ConfigDefaults {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the system-wide configuration directory path.
|
||||||
|
*
|
||||||
|
* @return the system config directory
|
||||||
|
*/
|
||||||
|
public static Path getSystemConfigDir() {
|
||||||
|
return switch (OperatingSystem.current()) {
|
||||||
|
case WINDOWS -> {
|
||||||
|
String programData = System.getenv("PROGRAMDATA");
|
||||||
|
if (programData == null || programData.isBlank()) {
|
||||||
|
programData = "C:\\ProgramData";
|
||||||
|
}
|
||||||
|
yield Path.of(programData, "barn");
|
||||||
|
}
|
||||||
|
case LINUX, MACOS -> Path.of("/etc/barn");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the user-specific configuration directory path.
|
||||||
|
*
|
||||||
|
* @return the user config directory
|
||||||
|
*/
|
||||||
|
public static Path getUserConfigDir() {
|
||||||
|
String userHome = System.getProperty("user.home", "");
|
||||||
|
return switch (OperatingSystem.current()) {
|
||||||
|
case WINDOWS -> {
|
||||||
|
String appData = System.getenv("APPDATA");
|
||||||
|
if (appData == null || appData.isBlank()) {
|
||||||
|
appData = Path.of(userHome, "AppData", "Roaming").toString();
|
||||||
|
}
|
||||||
|
yield Path.of(appData, "barn");
|
||||||
|
}
|
||||||
|
case MACOS -> Path.of(userHome, "Library", "Application Support", "barn");
|
||||||
|
case LINUX -> Path.of(userHome, ".config", "barn");
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets the list of configuration file paths in priority order.
|
* Gets the list of configuration file paths in priority order.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -186,11 +186,17 @@ public final class ConfigLoader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private Config buildConfig(Map<String, Map<String, Object>> data) {
|
private Config buildConfig(Map<String, Map<String, Object>> data) {
|
||||||
|
// Merge both "load_levels" (from TOML) and "loadlevels" (from env vars)
|
||||||
|
// Env vars (loadlevels) take precedence over config file (load_levels)
|
||||||
|
Map<String, Object> loadLevelData = new HashMap<>(data.getOrDefault("load_levels", Map.of()));
|
||||||
|
loadLevelData.putAll(data.getOrDefault("loadlevels", Map.of()));
|
||||||
|
|
||||||
return new Config(
|
return new Config(
|
||||||
buildServiceConfig(data.getOrDefault("service", Map.of())),
|
buildServiceConfig(data.getOrDefault("service", Map.of())),
|
||||||
buildJobsConfig(data.getOrDefault("jobs", Map.of())),
|
buildJobsConfig(data.getOrDefault("jobs", Map.of())),
|
||||||
buildCleanupConfig(data.getOrDefault("cleanup", Map.of())),
|
buildCleanupConfig(data.getOrDefault("cleanup", Map.of())),
|
||||||
buildStorageConfig(data.getOrDefault("storage", Map.of()))
|
buildStorageConfig(data.getOrDefault("storage", Map.of())),
|
||||||
|
buildLoadLevelConfig(loadLevelData)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -250,6 +256,17 @@ public final class ConfigLoader {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private LoadLevelConfig buildLoadLevelConfig(Map<String, Object> data) {
|
||||||
|
return new LoadLevelConfig(
|
||||||
|
getOrDefault(data, "max_high_jobs", LoadLevelConfig.DEFAULT_MAX_HIGH_JOBS,
|
||||||
|
this::toInt),
|
||||||
|
getOrDefault(data, "max_medium_jobs", LoadLevelConfig.DEFAULT_MAX_MEDIUM_JOBS,
|
||||||
|
this::toInt),
|
||||||
|
getOrDefault(data, "max_low_jobs", LoadLevelConfig.DEFAULT_MAX_LOW_JOBS,
|
||||||
|
this::toInt)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private <T> T getOrDefault(Map<String, Object> data, String key, T defaultValue,
|
private <T> T getOrDefault(Map<String, Object> data, String key, T defaultValue,
|
||||||
Function<Object, T> converter) {
|
Function<Object, T> converter) {
|
||||||
|
|||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package com.samsonmedia.barn.config;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses load level whitelist files (.load files).
|
||||||
|
*
|
||||||
|
* <p>Load files use a gitignore-like format:
|
||||||
|
* <ul>
|
||||||
|
* <li>Lines starting with # are comments</li>
|
||||||
|
* <li>Empty lines are ignored</li>
|
||||||
|
* <li>Plain names (e.g., "ffmpeg") match any executable with that name</li>
|
||||||
|
* <li>Full paths (e.g., "/usr/bin/ffmpeg") match that exact path</li>
|
||||||
|
* <li>Directories with trailing slash (e.g., "/opt/encoders/") match any executable in that directory</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
public final class LoadFileParser {
|
||||||
|
|
||||||
|
private LoadFileParser() {
|
||||||
|
// Utility class
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a load file into a list of command matchers.
|
||||||
|
*
|
||||||
|
* @param path the path to the load file
|
||||||
|
* @return a list of matchers, in file order
|
||||||
|
* @throws IOException if the file cannot be read
|
||||||
|
*/
|
||||||
|
public static List<CommandMatcher> parse(Path path) throws IOException {
|
||||||
|
Objects.requireNonNull(path, "path must not be null");
|
||||||
|
|
||||||
|
List<String> lines = Files.readAllLines(path);
|
||||||
|
List<CommandMatcher> matchers = new ArrayList<>();
|
||||||
|
|
||||||
|
for (String line : lines) {
|
||||||
|
String trimmed = line.strip();
|
||||||
|
|
||||||
|
// Skip comments and empty lines
|
||||||
|
if (trimmed.isEmpty() || trimmed.startsWith("#")) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
matchers.add(createMatcher(trimmed));
|
||||||
|
}
|
||||||
|
|
||||||
|
return matchers;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a load file if it exists, otherwise returns an empty list.
|
||||||
|
*
|
||||||
|
* @param path the path to the load file
|
||||||
|
* @return a list of matchers, or empty list if file doesn't exist
|
||||||
|
*/
|
||||||
|
public static List<CommandMatcher> parseIfExists(Path path) {
|
||||||
|
Objects.requireNonNull(path, "path must not be null");
|
||||||
|
|
||||||
|
if (!Files.exists(path)) {
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return parse(path);
|
||||||
|
} catch (IOException e) {
|
||||||
|
// Log and return empty list for robustness
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static CommandMatcher createMatcher(String entry) {
|
||||||
|
// Directory matcher: ends with /
|
||||||
|
if (entry.endsWith("/")) {
|
||||||
|
return new CommandMatcher.Directory(Path.of(entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full path matcher: contains path separator
|
||||||
|
if (entry.contains("/")) {
|
||||||
|
return new CommandMatcher.FullPath(Path.of(entry));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Executable name matcher: just a name
|
||||||
|
return new CommandMatcher.ExecutableName(entry);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
package com.samsonmedia.barn.config;
|
||||||
|
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import com.samsonmedia.barn.jobs.LoadLevel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration for per-load-level job limits.
|
||||||
|
*
|
||||||
|
* <p>This configuration controls how many jobs of each load level can run
|
||||||
|
* concurrently. This allows the system to run many lightweight tasks (like
|
||||||
|
* file downloads) while limiting resource-intensive tasks (like transcoding).
|
||||||
|
*
|
||||||
|
* @param maxHighJobs maximum concurrent high load jobs
|
||||||
|
* @param maxMediumJobs maximum concurrent medium load jobs
|
||||||
|
* @param maxLowJobs maximum concurrent low load jobs
|
||||||
|
*/
|
||||||
|
public record LoadLevelConfig(
|
||||||
|
int maxHighJobs,
|
||||||
|
int maxMediumJobs,
|
||||||
|
int maxLowJobs
|
||||||
|
) {
|
||||||
|
|
||||||
|
/** Default maximum high load jobs. */
|
||||||
|
public static final int DEFAULT_MAX_HIGH_JOBS = LoadLevel.HIGH.getDefaultMaxJobs();
|
||||||
|
|
||||||
|
/** Default maximum medium load jobs. */
|
||||||
|
public static final int DEFAULT_MAX_MEDIUM_JOBS = LoadLevel.MEDIUM.getDefaultMaxJobs();
|
||||||
|
|
||||||
|
/** Default maximum low load jobs. */
|
||||||
|
public static final int DEFAULT_MAX_LOW_JOBS = LoadLevel.LOW.getDefaultMaxJobs();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a LoadLevelConfig with validation.
|
||||||
|
*/
|
||||||
|
public LoadLevelConfig {
|
||||||
|
if (maxHighJobs < 1) {
|
||||||
|
throw new IllegalArgumentException("maxHighJobs must be at least 1");
|
||||||
|
}
|
||||||
|
if (maxMediumJobs < 1) {
|
||||||
|
throw new IllegalArgumentException("maxMediumJobs must be at least 1");
|
||||||
|
}
|
||||||
|
if (maxLowJobs < 1) {
|
||||||
|
throw new IllegalArgumentException("maxLowJobs must be at least 1");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a LoadLevelConfig with default values.
|
||||||
|
*
|
||||||
|
* @return a LoadLevelConfig with all defaults
|
||||||
|
*/
|
||||||
|
public static LoadLevelConfig withDefaults() {
|
||||||
|
return new LoadLevelConfig(
|
||||||
|
DEFAULT_MAX_HIGH_JOBS,
|
||||||
|
DEFAULT_MAX_MEDIUM_JOBS,
|
||||||
|
DEFAULT_MAX_LOW_JOBS
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a LoadLevelConfig from a total limit (for backward compatibility).
|
||||||
|
*
|
||||||
|
* <p>Distributes the total limit proportionally based on default ratios:
|
||||||
|
* HIGH gets ~5%, MEDIUM gets ~19%, LOW gets ~76% (matching default 2:8:32 ratio).
|
||||||
|
*
|
||||||
|
* @param totalLimit the total maximum concurrent jobs
|
||||||
|
* @return a LoadLevelConfig with proportional limits
|
||||||
|
* @deprecated Use explicit per-level limits instead
|
||||||
|
*/
|
||||||
|
@Deprecated
|
||||||
|
public static LoadLevelConfig fromTotalLimit(int totalLimit) {
|
||||||
|
if (totalLimit < 3) {
|
||||||
|
// Minimum: 1 for each level
|
||||||
|
return new LoadLevelConfig(1, 1, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use default ratio of 2:8:32 = 1:4:16
|
||||||
|
int totalRatio = 1 + 4 + 16; // 21
|
||||||
|
int high = Math.max(1, (totalLimit * 1) / totalRatio);
|
||||||
|
int medium = Math.max(1, (totalLimit * 4) / totalRatio);
|
||||||
|
int low = Math.max(1, totalLimit - high - medium);
|
||||||
|
|
||||||
|
return new LoadLevelConfig(high, medium, low);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the maximum concurrent jobs for the specified load level.
|
||||||
|
*
|
||||||
|
* @param level the load level
|
||||||
|
* @return the maximum concurrent jobs for that level
|
||||||
|
*/
|
||||||
|
public int getMaxJobsFor(LoadLevel level) {
|
||||||
|
Objects.requireNonNull(level, "level must not be null");
|
||||||
|
return switch (level) {
|
||||||
|
case HIGH -> maxHighJobs;
|
||||||
|
case MEDIUM -> maxMediumJobs;
|
||||||
|
case LOW -> maxLowJobs;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the total maximum concurrent jobs across all levels.
|
||||||
|
*
|
||||||
|
* @return the sum of all level limits
|
||||||
|
*/
|
||||||
|
public int getTotalMaxJobs() {
|
||||||
|
return maxHighJobs + maxMediumJobs + maxLowJobs;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -209,7 +209,7 @@ public class JobRunner {
|
|||||||
job.id(), job.state(), job.command(), job.tag(),
|
job.id(), job.state(), job.command(), job.tag(),
|
||||||
job.createdAt(), job.startedAt(), job.finishedAt(),
|
job.createdAt(), job.startedAt(), job.finishedAt(),
|
||||||
exitCode, job.error(), job.pid(), job.heartbeat(),
|
exitCode, job.error(), job.pid(), job.heartbeat(),
|
||||||
job.retryCount(), job.retryAt()
|
job.retryCount(), job.retryAt(), job.loadLevel()
|
||||||
);
|
);
|
||||||
return retryCalculator.shouldRetry(jobWithExitCode);
|
return retryCalculator.shouldRetry(jobWithExitCode);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,9 @@ import java.io.IOException;
|
|||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
import java.time.Instant;
|
import java.time.Instant;
|
||||||
import java.util.Comparator;
|
import java.util.Comparator;
|
||||||
|
import java.util.EnumMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
import java.util.Optional;
|
import java.util.Optional;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
@@ -15,8 +17,10 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
|||||||
import java.util.concurrent.atomic.AtomicInteger;
|
import java.util.concurrent.atomic.AtomicInteger;
|
||||||
|
|
||||||
import com.samsonmedia.barn.config.Config;
|
import com.samsonmedia.barn.config.Config;
|
||||||
|
import com.samsonmedia.barn.config.LoadLevelConfig;
|
||||||
import com.samsonmedia.barn.jobs.Job;
|
import com.samsonmedia.barn.jobs.Job;
|
||||||
import com.samsonmedia.barn.jobs.JobRepository;
|
import com.samsonmedia.barn.jobs.JobRepository;
|
||||||
|
import com.samsonmedia.barn.jobs.LoadLevel;
|
||||||
import com.samsonmedia.barn.logging.BarnLogger;
|
import com.samsonmedia.barn.logging.BarnLogger;
|
||||||
import com.samsonmedia.barn.state.BarnDirectories;
|
import com.samsonmedia.barn.state.BarnDirectories;
|
||||||
import com.samsonmedia.barn.state.JobState;
|
import com.samsonmedia.barn.state.JobState;
|
||||||
@@ -36,12 +40,12 @@ public class JobScheduler {
|
|||||||
private final JobRepository repository;
|
private final JobRepository repository;
|
||||||
private final JobRunner runner;
|
private final JobRunner runner;
|
||||||
private final BarnDirectories dirs;
|
private final BarnDirectories dirs;
|
||||||
private final int maxConcurrentJobs;
|
private final LoadLevelConfig loadLevelConfig;
|
||||||
private final Duration pollInterval;
|
private final Duration pollInterval;
|
||||||
private final Duration shutdownTimeout;
|
private final Duration shutdownTimeout;
|
||||||
|
|
||||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||||
private final AtomicInteger runningJobCount = new AtomicInteger(0);
|
private final Map<LoadLevel, AtomicInteger> runningJobCounts;
|
||||||
|
|
||||||
private ExecutorService jobExecutor;
|
private ExecutorService jobExecutor;
|
||||||
private ScheduledExecutorService schedulerThread;
|
private ScheduledExecutorService schedulerThread;
|
||||||
@@ -61,13 +65,17 @@ public class JobScheduler {
|
|||||||
BarnDirectories dirs,
|
BarnDirectories dirs,
|
||||||
Config config) {
|
Config config) {
|
||||||
this(repository, runner, dirs,
|
this(repository, runner, dirs,
|
||||||
config.service().maxConcurrentJobs(),
|
config.loadLevels(),
|
||||||
DEFAULT_POLL_INTERVAL,
|
DEFAULT_POLL_INTERVAL,
|
||||||
DEFAULT_SHUTDOWN_TIMEOUT);
|
DEFAULT_SHUTDOWN_TIMEOUT);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a JobScheduler with custom settings.
|
* Creates a JobScheduler with custom settings using legacy single-limit mode.
|
||||||
|
*
|
||||||
|
* <p>In legacy mode, all jobs are treated as MEDIUM load level, and the
|
||||||
|
* maxConcurrentJobs limit applies only to MEDIUM jobs. HIGH and LOW levels
|
||||||
|
* use their default limits.
|
||||||
*
|
*
|
||||||
* @param repository the job repository
|
* @param repository the job repository
|
||||||
* @param runner the job runner
|
* @param runner the job runner
|
||||||
@@ -75,7 +83,9 @@ public class JobScheduler {
|
|||||||
* @param maxConcurrentJobs the maximum number of concurrent jobs
|
* @param maxConcurrentJobs the maximum number of concurrent jobs
|
||||||
* @param pollInterval the interval between queue checks
|
* @param pollInterval the interval between queue checks
|
||||||
* @param shutdownTimeout the maximum time to wait for shutdown
|
* @param shutdownTimeout the maximum time to wait for shutdown
|
||||||
|
* @deprecated Use the constructor with LoadLevelConfig instead
|
||||||
*/
|
*/
|
||||||
|
@Deprecated
|
||||||
public JobScheduler(
|
public JobScheduler(
|
||||||
JobRepository repository,
|
JobRepository repository,
|
||||||
JobRunner runner,
|
JobRunner runner,
|
||||||
@@ -83,19 +93,49 @@ public class JobScheduler {
|
|||||||
int maxConcurrentJobs,
|
int maxConcurrentJobs,
|
||||||
Duration pollInterval,
|
Duration pollInterval,
|
||||||
Duration shutdownTimeout) {
|
Duration shutdownTimeout) {
|
||||||
|
this(repository, runner, dirs,
|
||||||
|
createLegacyConfig(maxConcurrentJobs),
|
||||||
|
pollInterval,
|
||||||
|
shutdownTimeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
private static LoadLevelConfig createLegacyConfig(int maxConcurrentJobs) {
|
||||||
|
if (maxConcurrentJobs <= 0) {
|
||||||
|
throw new IllegalArgumentException("maxConcurrentJobs must be positive: " + maxConcurrentJobs);
|
||||||
|
}
|
||||||
|
// In legacy mode, apply limit to MEDIUM only, use minimum for others
|
||||||
|
return new LoadLevelConfig(1, maxConcurrentJobs, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a JobScheduler with per-level limits.
|
||||||
|
*
|
||||||
|
* @param repository the job repository
|
||||||
|
* @param runner the job runner
|
||||||
|
* @param dirs the directory manager
|
||||||
|
* @param loadLevelConfig the per-level job limits
|
||||||
|
* @param pollInterval the interval between queue checks
|
||||||
|
* @param shutdownTimeout the maximum time to wait for shutdown
|
||||||
|
*/
|
||||||
|
public JobScheduler(
|
||||||
|
JobRepository repository,
|
||||||
|
JobRunner runner,
|
||||||
|
BarnDirectories dirs,
|
||||||
|
LoadLevelConfig loadLevelConfig,
|
||||||
|
Duration pollInterval,
|
||||||
|
Duration shutdownTimeout) {
|
||||||
this.repository = Objects.requireNonNull(repository, "repository must not be null");
|
this.repository = Objects.requireNonNull(repository, "repository must not be null");
|
||||||
this.runner = Objects.requireNonNull(runner, "runner 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.dirs = Objects.requireNonNull(dirs, "dirs must not be null");
|
||||||
this.maxConcurrentJobs = validatePositive(maxConcurrentJobs, "maxConcurrentJobs");
|
this.loadLevelConfig = Objects.requireNonNull(loadLevelConfig, "loadLevelConfig must not be null");
|
||||||
this.pollInterval = Objects.requireNonNull(pollInterval, "pollInterval must not be null");
|
this.pollInterval = Objects.requireNonNull(pollInterval, "pollInterval must not be null");
|
||||||
this.shutdownTimeout = Objects.requireNonNull(shutdownTimeout, "shutdownTimeout must not be null");
|
this.shutdownTimeout = Objects.requireNonNull(shutdownTimeout, "shutdownTimeout must not be null");
|
||||||
}
|
|
||||||
|
|
||||||
private static int validatePositive(int value, String name) {
|
// Initialize per-level running job counts
|
||||||
if (value <= 0) {
|
this.runningJobCounts = new EnumMap<>(LoadLevel.class);
|
||||||
throw new IllegalArgumentException(name + " must be positive: " + value);
|
for (LoadLevel level : LoadLevel.values()) {
|
||||||
|
runningJobCounts.put(level, new AtomicInteger(0));
|
||||||
}
|
}
|
||||||
return value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -118,8 +158,10 @@ public class JobScheduler {
|
|||||||
}
|
}
|
||||||
lock = acquired.get();
|
lock = acquired.get();
|
||||||
|
|
||||||
|
int totalMaxJobs = loadLevelConfig.getTotalMaxJobs();
|
||||||
|
|
||||||
// Create executors
|
// Create executors
|
||||||
jobExecutor = Executors.newFixedThreadPool(maxConcurrentJobs, r -> {
|
jobExecutor = Executors.newFixedThreadPool(totalMaxJobs, r -> {
|
||||||
Thread t = new Thread(r, "job-executor");
|
Thread t = new Thread(r, "job-executor");
|
||||||
t.setDaemon(true);
|
t.setDaemon(true);
|
||||||
return t;
|
return t;
|
||||||
@@ -141,7 +183,11 @@ public class JobScheduler {
|
|||||||
TimeUnit.MILLISECONDS
|
TimeUnit.MILLISECONDS
|
||||||
);
|
);
|
||||||
|
|
||||||
LOG.info("Scheduler started with max {} concurrent jobs", maxConcurrentJobs);
|
LOG.info("Scheduler started with per-level limits: HIGH={}, MEDIUM={}, LOW={} (total={})",
|
||||||
|
loadLevelConfig.maxHighJobs(),
|
||||||
|
loadLevelConfig.maxMediumJobs(),
|
||||||
|
loadLevelConfig.maxLowJobs(),
|
||||||
|
totalMaxJobs);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -241,11 +287,21 @@ public class JobScheduler {
|
|||||||
LOG.warn("Failed to count queued jobs: {}", e.getMessage());
|
LOG.warn("Failed to count queued jobs: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int totalRunning = runningJobCounts.values().stream()
|
||||||
|
.mapToInt(AtomicInteger::get)
|
||||||
|
.sum();
|
||||||
|
|
||||||
return new SchedulerStatus(
|
return new SchedulerStatus(
|
||||||
runningJobCount.get(),
|
totalRunning,
|
||||||
queuedCount,
|
queuedCount,
|
||||||
maxConcurrentJobs,
|
loadLevelConfig.getTotalMaxJobs(),
|
||||||
running.get()
|
running.get(),
|
||||||
|
runningJobCounts.get(LoadLevel.HIGH).get(),
|
||||||
|
runningJobCounts.get(LoadLevel.MEDIUM).get(),
|
||||||
|
runningJobCounts.get(LoadLevel.LOW).get(),
|
||||||
|
loadLevelConfig.maxHighJobs(),
|
||||||
|
loadLevelConfig.maxMediumJobs(),
|
||||||
|
loadLevelConfig.maxLowJobs()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -264,64 +320,91 @@ public class JobScheduler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// Check if we have capacity
|
// Find next queued job that has capacity in its load level
|
||||||
int currentRunning = runningJobCount.get();
|
Optional<Job> nextJob = findNextQueuedWithCapacity();
|
||||||
if (currentRunning >= maxConcurrentJobs) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Find next queued job
|
|
||||||
Optional<Job> nextJob = findNextQueued();
|
|
||||||
if (nextJob.isEmpty()) {
|
if (nextJob.isEmpty()) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
Job job = nextJob.get();
|
Job job = nextJob.get();
|
||||||
|
LoadLevel level = job.loadLevel();
|
||||||
|
|
||||||
// Check if job is ready (not scheduled for later retry)
|
// Check if job is ready (not scheduled for later retry)
|
||||||
if (job.retryAt() != null && job.retryAt().isAfter(Instant.now())) {
|
if (job.retryAt() != null && job.retryAt().isAfter(Instant.now())) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Increment count and submit
|
// Increment count for this level and submit
|
||||||
runningJobCount.incrementAndGet();
|
runningJobCounts.get(level).incrementAndGet();
|
||||||
|
|
||||||
jobExecutor.submit(() -> {
|
jobExecutor.submit(() -> {
|
||||||
try {
|
try {
|
||||||
runner.run(job);
|
runner.run(job);
|
||||||
} finally {
|
} finally {
|
||||||
runningJobCount.decrementAndGet();
|
runningJobCounts.get(level).decrementAndGet();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
LOG.debug("Scheduled job: {}", job.id());
|
LOG.debug("Scheduled job: {} (level={})", job.id(), level);
|
||||||
|
|
||||||
} catch (IOException e) {
|
} catch (IOException e) {
|
||||||
LOG.error("Error in scheduler: {}", e.getMessage(), e);
|
LOG.error("Error in scheduler: {}", e.getMessage(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private Optional<Job> findNextQueued() throws IOException {
|
private Optional<Job> findNextQueuedWithCapacity() throws IOException {
|
||||||
List<Job> queuedJobs = repository.findByState(JobState.QUEUED);
|
List<Job> queuedJobs = repository.findByState(JobState.QUEUED);
|
||||||
|
|
||||||
// Sort by creation time (FIFO)
|
// Sort by creation time (FIFO) and filter by retry time and capacity
|
||||||
return queuedJobs.stream()
|
return queuedJobs.stream()
|
||||||
.filter(job -> job.retryAt() == null || !job.retryAt().isAfter(Instant.now()))
|
.filter(job -> job.retryAt() == null || !job.retryAt().isAfter(Instant.now()))
|
||||||
|
.filter(this::hasCapacityForLevel)
|
||||||
.min(Comparator.comparing(Job::createdAt));
|
.min(Comparator.comparing(Job::createdAt));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean hasCapacityForLevel(Job job) {
|
||||||
|
LoadLevel level = job.loadLevel();
|
||||||
|
int currentRunning = runningJobCounts.get(level).get();
|
||||||
|
int maxForLevel = loadLevelConfig.getMaxJobsFor(level);
|
||||||
|
return currentRunning < maxForLevel;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Status of the job scheduler.
|
* Status of the job scheduler.
|
||||||
*
|
*
|
||||||
* @param runningJobs the number of currently running jobs
|
* @param runningJobs the total number of currently running jobs
|
||||||
* @param queuedJobs the number of queued jobs
|
* @param queuedJobs the number of queued jobs
|
||||||
* @param maxConcurrentJobs the maximum concurrent job limit
|
* @param maxConcurrentJobs the total maximum concurrent job limit
|
||||||
* @param isRunning whether the scheduler is running
|
* @param isRunning whether the scheduler is running
|
||||||
|
* @param runningHighJobs running HIGH load level jobs
|
||||||
|
* @param runningMediumJobs running MEDIUM load level jobs
|
||||||
|
* @param runningLowJobs running LOW load level jobs
|
||||||
|
* @param maxHighJobs maximum HIGH load level jobs
|
||||||
|
* @param maxMediumJobs maximum MEDIUM load level jobs
|
||||||
|
* @param maxLowJobs maximum LOW load level jobs
|
||||||
*/
|
*/
|
||||||
public record SchedulerStatus(
|
public record SchedulerStatus(
|
||||||
int runningJobs,
|
int runningJobs,
|
||||||
int queuedJobs,
|
int queuedJobs,
|
||||||
int maxConcurrentJobs,
|
int maxConcurrentJobs,
|
||||||
boolean isRunning
|
boolean isRunning,
|
||||||
) { }
|
int runningHighJobs,
|
||||||
|
int runningMediumJobs,
|
||||||
|
int runningLowJobs,
|
||||||
|
int maxHighJobs,
|
||||||
|
int maxMediumJobs,
|
||||||
|
int maxLowJobs
|
||||||
|
) {
|
||||||
|
/**
|
||||||
|
* Creates a SchedulerStatus with only legacy fields (for backward compatibility).
|
||||||
|
*
|
||||||
|
* @param runningJobs the total number of currently running jobs
|
||||||
|
* @param queuedJobs the number of queued jobs
|
||||||
|
* @param maxConcurrentJobs the total maximum concurrent job limit
|
||||||
|
* @param isRunning whether the scheduler is running
|
||||||
|
*/
|
||||||
|
public SchedulerStatus(int runningJobs, int queuedJobs, int maxConcurrentJobs, boolean isRunning) {
|
||||||
|
this(runningJobs, queuedJobs, maxConcurrentJobs, isRunning, 0, 0, 0, 0, 0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -25,6 +25,7 @@ import com.samsonmedia.barn.state.JobState;
|
|||||||
* @param heartbeat last liveness check timestamp
|
* @param heartbeat last liveness check timestamp
|
||||||
* @param retryCount current retry attempt (0-based)
|
* @param retryCount current retry attempt (0-based)
|
||||||
* @param retryAt when to retry (null if not scheduled for retry)
|
* @param retryAt when to retry (null if not scheduled for retry)
|
||||||
|
* @param loadLevel the load level classification for this job
|
||||||
*/
|
*/
|
||||||
public record Job(
|
public record Job(
|
||||||
String id,
|
String id,
|
||||||
@@ -39,7 +40,8 @@ public record Job(
|
|||||||
Long pid,
|
Long pid,
|
||||||
Instant heartbeat,
|
Instant heartbeat,
|
||||||
int retryCount,
|
int retryCount,
|
||||||
Instant retryAt
|
Instant retryAt,
|
||||||
|
LoadLevel loadLevel
|
||||||
) {
|
) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -50,6 +52,7 @@ public record Job(
|
|||||||
Objects.requireNonNull(state, "state must not be null");
|
Objects.requireNonNull(state, "state must not be null");
|
||||||
Objects.requireNonNull(command, "command must not be null");
|
Objects.requireNonNull(command, "command must not be null");
|
||||||
Objects.requireNonNull(createdAt, "createdAt must not be null");
|
Objects.requireNonNull(createdAt, "createdAt must not be null");
|
||||||
|
Objects.requireNonNull(loadLevel, "loadLevel must not be null");
|
||||||
if (id.isBlank()) {
|
if (id.isBlank()) {
|
||||||
throw new IllegalArgumentException("id must not be blank");
|
throw new IllegalArgumentException("id must not be blank");
|
||||||
}
|
}
|
||||||
@@ -68,9 +71,22 @@ public record Job(
|
|||||||
* @param id the job ID
|
* @param id the job ID
|
||||||
* @param command the command to execute
|
* @param command the command to execute
|
||||||
* @param tag optional tag (may be null)
|
* @param tag optional tag (may be null)
|
||||||
* @return a new Job in QUEUED state
|
* @return a new Job in QUEUED state with MEDIUM load level
|
||||||
*/
|
*/
|
||||||
public static Job createQueued(String id, List<String> command, String tag) {
|
public static Job createQueued(String id, List<String> command, String tag) {
|
||||||
|
return createQueued(id, command, tag, LoadLevel.getDefault());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new queued job with specified load level.
|
||||||
|
*
|
||||||
|
* @param id the job ID
|
||||||
|
* @param command the command to execute
|
||||||
|
* @param tag optional tag (may be null)
|
||||||
|
* @param loadLevel the load level for this job
|
||||||
|
* @return a new Job in QUEUED state
|
||||||
|
*/
|
||||||
|
public static Job createQueued(String id, List<String> command, String tag, LoadLevel loadLevel) {
|
||||||
return new Job(
|
return new Job(
|
||||||
id,
|
id,
|
||||||
JobState.QUEUED,
|
JobState.QUEUED,
|
||||||
@@ -84,7 +100,8 @@ public record Job(
|
|||||||
null, // pid
|
null, // pid
|
||||||
null, // heartbeat
|
null, // heartbeat
|
||||||
0, // retryCount
|
0, // retryCount
|
||||||
null // retryAt
|
null, // retryAt
|
||||||
|
loadLevel
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -96,7 +113,18 @@ public record Job(
|
|||||||
*/
|
*/
|
||||||
public Job withState(JobState newState) {
|
public Job withState(JobState newState) {
|
||||||
return new Job(id, newState, command, tag, createdAt, startedAt, finishedAt,
|
return new Job(id, newState, command, tag, createdAt, startedAt, finishedAt,
|
||||||
exitCode, error, pid, heartbeat, retryCount, retryAt);
|
exitCode, error, pid, heartbeat, retryCount, retryAt, loadLevel);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a copy of this job with a new load level.
|
||||||
|
*
|
||||||
|
* @param newLoadLevel the new load level
|
||||||
|
* @return a new Job with the updated load level
|
||||||
|
*/
|
||||||
|
public Job withLoadLevel(LoadLevel newLoadLevel) {
|
||||||
|
return new Job(id, state, command, tag, createdAt, startedAt, finishedAt,
|
||||||
|
exitCode, error, pid, heartbeat, retryCount, retryAt, newLoadLevel);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -108,7 +136,7 @@ public record Job(
|
|||||||
public Job withStarted(long processId) {
|
public Job withStarted(long processId) {
|
||||||
Instant now = Instant.now();
|
Instant now = Instant.now();
|
||||||
return new Job(id, JobState.RUNNING, command, tag, createdAt, now, finishedAt,
|
return new Job(id, JobState.RUNNING, command, tag, createdAt, now, finishedAt,
|
||||||
exitCode, error, processId, now, retryCount, retryAt);
|
exitCode, error, processId, now, retryCount, retryAt, loadLevel);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -121,7 +149,7 @@ public record Job(
|
|||||||
public Job withCompleted(int code, String errorMessage) {
|
public Job withCompleted(int code, String errorMessage) {
|
||||||
JobState newState = (code == 0) ? JobState.SUCCEEDED : JobState.FAILED;
|
JobState newState = (code == 0) ? JobState.SUCCEEDED : JobState.FAILED;
|
||||||
return new Job(id, newState, command, tag, createdAt, startedAt, Instant.now(),
|
return new Job(id, newState, command, tag, createdAt, startedAt, Instant.now(),
|
||||||
code, errorMessage, pid, heartbeat, retryCount, retryAt);
|
code, errorMessage, pid, heartbeat, retryCount, retryAt, loadLevel);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -132,7 +160,7 @@ public record Job(
|
|||||||
*/
|
*/
|
||||||
public Job withHeartbeat(Instant timestamp) {
|
public Job withHeartbeat(Instant timestamp) {
|
||||||
return new Job(id, state, command, tag, createdAt, startedAt, finishedAt,
|
return new Job(id, state, command, tag, createdAt, startedAt, finishedAt,
|
||||||
exitCode, error, pid, timestamp, retryCount, retryAt);
|
exitCode, error, pid, timestamp, retryCount, retryAt, loadLevel);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -143,7 +171,7 @@ public record Job(
|
|||||||
*/
|
*/
|
||||||
public Job withRetry(Instant retryTimestamp) {
|
public Job withRetry(Instant retryTimestamp) {
|
||||||
return new Job(id, JobState.QUEUED, command, tag, createdAt, null, null,
|
return new Job(id, JobState.QUEUED, command, tag, createdAt, null, null,
|
||||||
null, null, null, null, retryCount + 1, retryTimestamp);
|
null, null, null, null, retryCount + 1, retryTimestamp, loadLevel);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -153,7 +181,7 @@ public record Job(
|
|||||||
*/
|
*/
|
||||||
public Job withCanceled() {
|
public Job withCanceled() {
|
||||||
return new Job(id, JobState.CANCELED, command, tag, createdAt, startedAt, Instant.now(),
|
return new Job(id, JobState.CANCELED, command, tag, createdAt, startedAt, Instant.now(),
|
||||||
exitCode, "Job was canceled", pid, heartbeat, retryCount, retryAt);
|
exitCode, "Job was canceled", pid, heartbeat, retryCount, retryAt, loadLevel);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ import com.samsonmedia.barn.config.JobsConfig;
|
|||||||
* @param maxRetries maximum number of retry attempts
|
* @param maxRetries maximum number of retry attempts
|
||||||
* @param retryDelaySeconds initial delay before first retry
|
* @param retryDelaySeconds initial delay before first retry
|
||||||
* @param retryBackoffMultiplier multiplier for exponential backoff
|
* @param retryBackoffMultiplier multiplier for exponential backoff
|
||||||
|
* @param loadLevel the load level classification for this job
|
||||||
*/
|
*/
|
||||||
public record JobManifest(
|
public record JobManifest(
|
||||||
String id,
|
String id,
|
||||||
@@ -27,7 +28,8 @@ public record JobManifest(
|
|||||||
Instant createdAt,
|
Instant createdAt,
|
||||||
int maxRetries,
|
int maxRetries,
|
||||||
int retryDelaySeconds,
|
int retryDelaySeconds,
|
||||||
double retryBackoffMultiplier
|
double retryBackoffMultiplier,
|
||||||
|
LoadLevel loadLevel
|
||||||
) {
|
) {
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -37,6 +39,7 @@ public record JobManifest(
|
|||||||
Objects.requireNonNull(id, "id must not be null");
|
Objects.requireNonNull(id, "id must not be null");
|
||||||
Objects.requireNonNull(command, "command must not be null");
|
Objects.requireNonNull(command, "command must not be null");
|
||||||
Objects.requireNonNull(createdAt, "createdAt must not be null");
|
Objects.requireNonNull(createdAt, "createdAt must not be null");
|
||||||
|
Objects.requireNonNull(loadLevel, "loadLevel must not be null");
|
||||||
if (id.isBlank()) {
|
if (id.isBlank()) {
|
||||||
throw new IllegalArgumentException("id must not be blank");
|
throw new IllegalArgumentException("id must not be blank");
|
||||||
}
|
}
|
||||||
@@ -62,9 +65,24 @@ public record JobManifest(
|
|||||||
* @param command the command to execute
|
* @param command the command to execute
|
||||||
* @param tag optional tag (may be null)
|
* @param tag optional tag (may be null)
|
||||||
* @param config the jobs configuration for defaults
|
* @param config the jobs configuration for defaults
|
||||||
* @return a new JobManifest
|
* @return a new JobManifest with MEDIUM load level
|
||||||
*/
|
*/
|
||||||
public static JobManifest create(String id, List<String> command, String tag, JobsConfig config) {
|
public static JobManifest create(String id, List<String> command, String tag, JobsConfig config) {
|
||||||
|
return create(id, command, tag, config, LoadLevel.getDefault());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a JobManifest with default retry configuration from JobsConfig.
|
||||||
|
*
|
||||||
|
* @param id the job ID
|
||||||
|
* @param command the command to execute
|
||||||
|
* @param tag optional tag (may be null)
|
||||||
|
* @param config the jobs configuration for defaults
|
||||||
|
* @param loadLevel the load level for this job
|
||||||
|
* @return a new JobManifest
|
||||||
|
*/
|
||||||
|
public static JobManifest create(String id, List<String> command, String tag,
|
||||||
|
JobsConfig config, LoadLevel loadLevel) {
|
||||||
Objects.requireNonNull(config, "config must not be null");
|
Objects.requireNonNull(config, "config must not be null");
|
||||||
return new JobManifest(
|
return new JobManifest(
|
||||||
id,
|
id,
|
||||||
@@ -73,7 +91,8 @@ public record JobManifest(
|
|||||||
Instant.now(),
|
Instant.now(),
|
||||||
config.maxRetries(),
|
config.maxRetries(),
|
||||||
config.retryDelaySeconds(),
|
config.retryDelaySeconds(),
|
||||||
config.retryBackoffMultiplier()
|
config.retryBackoffMultiplier(),
|
||||||
|
loadLevel
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -86,10 +105,29 @@ public record JobManifest(
|
|||||||
* @param maxRetries maximum retry attempts
|
* @param maxRetries maximum retry attempts
|
||||||
* @param retryDelaySeconds initial retry delay
|
* @param retryDelaySeconds initial retry delay
|
||||||
* @param retryBackoffMultiplier backoff multiplier
|
* @param retryBackoffMultiplier backoff multiplier
|
||||||
* @return a new JobManifest
|
* @return a new JobManifest with MEDIUM load level
|
||||||
*/
|
*/
|
||||||
public static JobManifest create(String id, List<String> command, String tag,
|
public static JobManifest create(String id, List<String> command, String tag,
|
||||||
int maxRetries, int retryDelaySeconds, double retryBackoffMultiplier) {
|
int maxRetries, int retryDelaySeconds, double retryBackoffMultiplier) {
|
||||||
|
return create(id, command, tag, maxRetries, retryDelaySeconds, retryBackoffMultiplier,
|
||||||
|
LoadLevel.getDefault());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a JobManifest with custom retry configuration and load level.
|
||||||
|
*
|
||||||
|
* @param id the job ID
|
||||||
|
* @param command the command to execute
|
||||||
|
* @param tag optional tag (may be null)
|
||||||
|
* @param maxRetries maximum retry attempts
|
||||||
|
* @param retryDelaySeconds initial retry delay
|
||||||
|
* @param retryBackoffMultiplier backoff multiplier
|
||||||
|
* @param loadLevel the load level for this job
|
||||||
|
* @return a new JobManifest
|
||||||
|
*/
|
||||||
|
public static JobManifest create(String id, List<String> command, String tag,
|
||||||
|
int maxRetries, int retryDelaySeconds, double retryBackoffMultiplier,
|
||||||
|
LoadLevel loadLevel) {
|
||||||
return new JobManifest(
|
return new JobManifest(
|
||||||
id,
|
id,
|
||||||
command,
|
command,
|
||||||
@@ -97,7 +135,8 @@ public record JobManifest(
|
|||||||
Instant.now(),
|
Instant.now(),
|
||||||
maxRetries,
|
maxRetries,
|
||||||
retryDelaySeconds,
|
retryDelaySeconds,
|
||||||
retryBackoffMultiplier
|
retryBackoffMultiplier,
|
||||||
|
loadLevel
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -53,7 +53,7 @@ public class JobRepository {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a new job with the given command and configuration.
|
* Creates a new job with the given command and configuration using default load level.
|
||||||
*
|
*
|
||||||
* @param command the command to execute
|
* @param command the command to execute
|
||||||
* @param tag optional user tag (may be null)
|
* @param tag optional user tag (may be null)
|
||||||
@@ -62,11 +62,27 @@ public class JobRepository {
|
|||||||
* @throws IOException if creation fails
|
* @throws IOException if creation fails
|
||||||
*/
|
*/
|
||||||
public Job create(List<String> command, String tag, JobsConfig config) throws IOException {
|
public Job create(List<String> command, String tag, JobsConfig config) throws IOException {
|
||||||
|
return create(command, tag, config, LoadLevel.getDefault());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new job with the given command, configuration, and load level.
|
||||||
|
*
|
||||||
|
* @param command the command to execute
|
||||||
|
* @param tag optional user tag (may be null)
|
||||||
|
* @param config the jobs configuration for defaults
|
||||||
|
* @param loadLevel the load level classification for this job
|
||||||
|
* @return the created Job
|
||||||
|
* @throws IOException if creation fails
|
||||||
|
*/
|
||||||
|
public Job create(List<String> command, String tag, JobsConfig config, LoadLevel loadLevel)
|
||||||
|
throws IOException {
|
||||||
Objects.requireNonNull(command, "command must not be null");
|
Objects.requireNonNull(command, "command must not be null");
|
||||||
Objects.requireNonNull(config, "config must not be null");
|
Objects.requireNonNull(config, "config must not be null");
|
||||||
|
Objects.requireNonNull(loadLevel, "loadLevel must not be null");
|
||||||
|
|
||||||
String id = JobIdGenerator.generate();
|
String id = JobIdGenerator.generate();
|
||||||
JobManifest manifest = JobManifest.create(id, command, tag, config);
|
JobManifest manifest = JobManifest.create(id, command, tag, config, loadLevel);
|
||||||
|
|
||||||
// Create directories
|
// Create directories
|
||||||
dirs.createJobDirs(id);
|
dirs.createJobDirs(id);
|
||||||
@@ -86,7 +102,7 @@ public class JobRepository {
|
|||||||
stateFiles.writeRetryCount(0);
|
stateFiles.writeRetryCount(0);
|
||||||
|
|
||||||
LOG.info("Created job: {}", id);
|
LOG.info("Created job: {}", id);
|
||||||
return Job.createQueued(id, command, tag);
|
return Job.createQueued(id, command, tag, loadLevel);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -388,6 +404,12 @@ public class JobRepository {
|
|||||||
StateFiles stateFiles = new StateFiles(jobDir);
|
StateFiles stateFiles = new StateFiles(jobDir);
|
||||||
JobManifest manifest = loadManifest(id);
|
JobManifest manifest = loadManifest(id);
|
||||||
|
|
||||||
|
// For backward compatibility, use manifest's loadLevel (which defaults to MEDIUM)
|
||||||
|
// if no loadLevel field exists in manifest (old jobs)
|
||||||
|
LoadLevel loadLevel = manifest.loadLevel() != null
|
||||||
|
? manifest.loadLevel()
|
||||||
|
: LoadLevel.getDefault();
|
||||||
|
|
||||||
return new Job(
|
return new Job(
|
||||||
id,
|
id,
|
||||||
stateFiles.readState().orElse(JobState.QUEUED),
|
stateFiles.readState().orElse(JobState.QUEUED),
|
||||||
@@ -401,7 +423,8 @@ public class JobRepository {
|
|||||||
stateFiles.readPid().isPresent() ? stateFiles.readPid().getAsLong() : null,
|
stateFiles.readPid().isPresent() ? stateFiles.readPid().getAsLong() : null,
|
||||||
stateFiles.readHeartbeat().orElse(null),
|
stateFiles.readHeartbeat().orElse(null),
|
||||||
stateFiles.readRetryCount().orElse(0),
|
stateFiles.readRetryCount().orElse(0),
|
||||||
stateFiles.readRetryAt().orElse(null)
|
stateFiles.readRetryAt().orElse(null),
|
||||||
|
loadLevel
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
package com.samsonmedia.barn.jobs;
|
||||||
|
|
||||||
|
import java.util.Locale;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Load level classification for jobs.
|
||||||
|
*
|
||||||
|
* <p>Jobs are classified into load levels based on their resource intensity:
|
||||||
|
* <ul>
|
||||||
|
* <li>{@link #HIGH} - CPU/GPU intensive tasks like transcoding (default: 2 concurrent)</li>
|
||||||
|
* <li>{@link #MEDIUM} - General purpose tasks (default: 8 concurrent)</li>
|
||||||
|
* <li>{@link #LOW} - Network/IO intensive tasks like downloads (default: 32 concurrent)</li>
|
||||||
|
* </ul>
|
||||||
|
*/
|
||||||
|
public enum LoadLevel {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* High load level for CPU/GPU intensive tasks (e.g., ffmpeg, transcoding).
|
||||||
|
*/
|
||||||
|
HIGH(2),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Medium load level for general purpose tasks.
|
||||||
|
*/
|
||||||
|
MEDIUM(8),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Low load level for network/IO intensive tasks (e.g., curl, rclone).
|
||||||
|
*/
|
||||||
|
LOW(32);
|
||||||
|
|
||||||
|
private final int defaultMaxJobs;
|
||||||
|
|
||||||
|
LoadLevel(int defaultMaxJobs) {
|
||||||
|
this.defaultMaxJobs = defaultMaxJobs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the default maximum concurrent jobs for this load level.
|
||||||
|
*
|
||||||
|
* @return the default max jobs
|
||||||
|
*/
|
||||||
|
public int getDefaultMaxJobs() {
|
||||||
|
return defaultMaxJobs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the lowercase string representation of this load level.
|
||||||
|
*
|
||||||
|
* @return the lowercase string
|
||||||
|
*/
|
||||||
|
public String toLowercase() {
|
||||||
|
return name().toLowerCase(Locale.ROOT);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the default load level (MEDIUM).
|
||||||
|
*
|
||||||
|
* @return the default load level
|
||||||
|
*/
|
||||||
|
public static LoadLevel getDefault() {
|
||||||
|
return MEDIUM;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parses a load level from a string (case-insensitive).
|
||||||
|
*
|
||||||
|
* @param value the string value to parse
|
||||||
|
* @return the parsed LoadLevel
|
||||||
|
* @throws IllegalArgumentException if the value is not a valid load level
|
||||||
|
*/
|
||||||
|
public static LoadLevel fromString(String value) {
|
||||||
|
if (value == null || value.isBlank()) {
|
||||||
|
throw new IllegalArgumentException("Load level cannot be null or blank");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return valueOf(value.trim().toUpperCase(Locale.ROOT));
|
||||||
|
} catch (IllegalArgumentException e) {
|
||||||
|
throw new IllegalArgumentException(
|
||||||
|
"Invalid load level: '" + value + "'. Valid values are: high, medium, low");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
package com.samsonmedia.barn.jobs;
|
||||||
|
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Objects;
|
||||||
|
|
||||||
|
import com.samsonmedia.barn.config.CommandMatcher;
|
||||||
|
import com.samsonmedia.barn.config.ConfigDefaults;
|
||||||
|
import com.samsonmedia.barn.config.LoadFileParser;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Classifies commands into load levels based on whitelist files.
|
||||||
|
*
|
||||||
|
* <p>The classifier loads whitelist files from the config directory:
|
||||||
|
* <ul>
|
||||||
|
* <li>{@code high.load} - Commands that are CPU/GPU intensive (e.g., transcoding)</li>
|
||||||
|
* <li>{@code medium.load} - General purpose commands</li>
|
||||||
|
* <li>{@code low.load} - Commands that are network/IO intensive (e.g., downloads)</li>
|
||||||
|
* </ul>
|
||||||
|
*
|
||||||
|
* <p>Commands are matched against each list in priority order: HIGH, MEDIUM, LOW.
|
||||||
|
* If a command is not matched by any list, it defaults to MEDIUM.
|
||||||
|
*/
|
||||||
|
public final class LoadLevelClassifier {
|
||||||
|
|
||||||
|
/** File name for high load whitelist. */
|
||||||
|
public static final String HIGH_LOAD_FILE = "high.load";
|
||||||
|
|
||||||
|
/** File name for medium load whitelist. */
|
||||||
|
public static final String MEDIUM_LOAD_FILE = "medium.load";
|
||||||
|
|
||||||
|
/** File name for low load whitelist. */
|
||||||
|
public static final String LOW_LOAD_FILE = "low.load";
|
||||||
|
|
||||||
|
private final List<CommandMatcher> highMatchers;
|
||||||
|
private final List<CommandMatcher> mediumMatchers;
|
||||||
|
private final List<CommandMatcher> lowMatchers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a LoadLevelClassifier with the given matchers.
|
||||||
|
*
|
||||||
|
* @param highMatchers matchers for HIGH load level
|
||||||
|
* @param mediumMatchers matchers for MEDIUM load level
|
||||||
|
* @param lowMatchers matchers for LOW load level
|
||||||
|
*/
|
||||||
|
public LoadLevelClassifier(
|
||||||
|
List<CommandMatcher> highMatchers,
|
||||||
|
List<CommandMatcher> mediumMatchers,
|
||||||
|
List<CommandMatcher> lowMatchers) {
|
||||||
|
this.highMatchers = List.copyOf(Objects.requireNonNull(highMatchers, "highMatchers"));
|
||||||
|
this.mediumMatchers = List.copyOf(Objects.requireNonNull(mediumMatchers, "mediumMatchers"));
|
||||||
|
this.lowMatchers = List.copyOf(Objects.requireNonNull(lowMatchers, "lowMatchers"));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads a classifier from whitelist files in the specified directory.
|
||||||
|
*
|
||||||
|
* <p>If a whitelist file doesn't exist, an empty list is used for that level.
|
||||||
|
*
|
||||||
|
* @param configDir the directory containing whitelist files
|
||||||
|
* @return a new classifier
|
||||||
|
*/
|
||||||
|
public static LoadLevelClassifier load(Path configDir) {
|
||||||
|
Objects.requireNonNull(configDir, "configDir must not be null");
|
||||||
|
|
||||||
|
List<CommandMatcher> high = LoadFileParser.parseIfExists(configDir.resolve(HIGH_LOAD_FILE));
|
||||||
|
List<CommandMatcher> medium = LoadFileParser.parseIfExists(configDir.resolve(MEDIUM_LOAD_FILE));
|
||||||
|
List<CommandMatcher> low = LoadFileParser.parseIfExists(configDir.resolve(LOW_LOAD_FILE));
|
||||||
|
|
||||||
|
return new LoadLevelClassifier(high, medium, low);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Loads a classifier from the system config directory.
|
||||||
|
*
|
||||||
|
* <p>Searches for whitelist files in the system config directory
|
||||||
|
* (e.g., /etc/barn/ on Linux/macOS, %PROGRAMDATA%\barn\ on Windows).
|
||||||
|
*
|
||||||
|
* <p>If no config directory is found, returns a classifier with empty whitelists
|
||||||
|
* (all commands default to MEDIUM).
|
||||||
|
*
|
||||||
|
* @return a new classifier
|
||||||
|
*/
|
||||||
|
public static LoadLevelClassifier loadFromConfigDir() {
|
||||||
|
Path systemConfig = ConfigDefaults.getSystemConfigDir();
|
||||||
|
if (Files.isDirectory(systemConfig) && hasAnyLoadFile(systemConfig)) {
|
||||||
|
return load(systemConfig);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return empty classifier (all commands default to MEDIUM)
|
||||||
|
return new LoadLevelClassifier(List.of(), List.of(), List.of());
|
||||||
|
}
|
||||||
|
|
||||||
|
private static boolean hasAnyLoadFile(Path dir) {
|
||||||
|
return Files.exists(dir.resolve(HIGH_LOAD_FILE))
|
||||||
|
|| Files.exists(dir.resolve(MEDIUM_LOAD_FILE))
|
||||||
|
|| Files.exists(dir.resolve(LOW_LOAD_FILE));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Classifies a command into a load level.
|
||||||
|
*
|
||||||
|
* <p>Commands are checked against each whitelist in priority order:
|
||||||
|
* HIGH, MEDIUM, LOW. If a command matches multiple lists, the highest
|
||||||
|
* priority level wins. If no match is found, MEDIUM is returned.
|
||||||
|
*
|
||||||
|
* @param command the command and arguments (first element is the executable)
|
||||||
|
* @return the load level for this command
|
||||||
|
*/
|
||||||
|
public LoadLevel classify(List<String> command) {
|
||||||
|
Objects.requireNonNull(command, "command must not be null");
|
||||||
|
|
||||||
|
if (command.isEmpty()) {
|
||||||
|
return LoadLevel.getDefault();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check HIGH first (highest priority)
|
||||||
|
for (CommandMatcher matcher : highMatchers) {
|
||||||
|
if (matcher.matches(command)) {
|
||||||
|
return LoadLevel.HIGH;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check MEDIUM second
|
||||||
|
for (CommandMatcher matcher : mediumMatchers) {
|
||||||
|
if (matcher.matches(command)) {
|
||||||
|
return LoadLevel.MEDIUM;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check LOW third
|
||||||
|
for (CommandMatcher matcher : lowMatchers) {
|
||||||
|
if (matcher.matches(command)) {
|
||||||
|
return LoadLevel.LOW;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Default to MEDIUM
|
||||||
|
return LoadLevel.getDefault();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -21,6 +21,8 @@ import com.samsonmedia.barn.ipc.IpcException;
|
|||||||
import com.samsonmedia.barn.ipc.IpcServer;
|
import com.samsonmedia.barn.ipc.IpcServer;
|
||||||
import com.samsonmedia.barn.jobs.Job;
|
import com.samsonmedia.barn.jobs.Job;
|
||||||
import com.samsonmedia.barn.jobs.JobRepository;
|
import com.samsonmedia.barn.jobs.JobRepository;
|
||||||
|
import com.samsonmedia.barn.jobs.LoadLevel;
|
||||||
|
import com.samsonmedia.barn.jobs.LoadLevelClassifier;
|
||||||
import com.samsonmedia.barn.logging.BarnLogger;
|
import com.samsonmedia.barn.logging.BarnLogger;
|
||||||
import com.samsonmedia.barn.logging.LoggingConfig;
|
import com.samsonmedia.barn.logging.LoggingConfig;
|
||||||
import com.samsonmedia.barn.state.BarnDirectories;
|
import com.samsonmedia.barn.state.BarnDirectories;
|
||||||
@@ -48,6 +50,7 @@ public class BarnService {
|
|||||||
private final JobScheduler scheduler;
|
private final JobScheduler scheduler;
|
||||||
private final CleanupScheduler cleanupScheduler;
|
private final CleanupScheduler cleanupScheduler;
|
||||||
private final CrashRecovery crashRecovery;
|
private final CrashRecovery crashRecovery;
|
||||||
|
private final LoadLevelClassifier loadLevelClassifier;
|
||||||
private final CountDownLatch shutdownLatch;
|
private final CountDownLatch shutdownLatch;
|
||||||
private final AtomicBoolean running;
|
private final AtomicBoolean running;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
@@ -71,6 +74,9 @@ public class BarnService {
|
|||||||
HeartbeatChecker heartbeatChecker = new HeartbeatChecker(heartbeatThreshold);
|
HeartbeatChecker heartbeatChecker = new HeartbeatChecker(heartbeatThreshold);
|
||||||
this.crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs, config);
|
this.crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs, config);
|
||||||
|
|
||||||
|
// Load classifier from config directory (if .load files exist)
|
||||||
|
this.loadLevelClassifier = LoadLevelClassifier.loadFromConfigDir();
|
||||||
|
|
||||||
this.shutdownLatch = new CountDownLatch(1);
|
this.shutdownLatch = new CountDownLatch(1);
|
||||||
this.running = new AtomicBoolean(false);
|
this.running = new AtomicBoolean(false);
|
||||||
this.objectMapper = new ObjectMapper();
|
this.objectMapper = new ObjectMapper();
|
||||||
@@ -316,9 +322,10 @@ public class BarnService {
|
|||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
List<String> command = (List<String>) map.get("command");
|
List<String> command = (List<String>) map.get("command");
|
||||||
String tag = (String) map.get("tag");
|
final String tag = (String) map.get("tag");
|
||||||
Integer maxRetries = (Integer) map.get("maxRetries");
|
final String loadLevelStr = (String) map.get("loadLevel");
|
||||||
Integer retryDelaySeconds = (Integer) map.get("retryDelaySeconds");
|
final Integer maxRetries = (Integer) map.get("maxRetries");
|
||||||
|
final Integer retryDelaySeconds = (Integer) map.get("retryDelaySeconds");
|
||||||
|
|
||||||
if (command == null || command.isEmpty()) {
|
if (command == null || command.isEmpty()) {
|
||||||
throw new IpcException("INVALID_REQUEST", "Command is required");
|
throw new IpcException("INVALID_REQUEST", "Command is required");
|
||||||
@@ -335,8 +342,18 @@ public class BarnService {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Job job = repository.create(command, tag, jobsConfig);
|
// Determine load level: use explicit override, or auto-classify
|
||||||
LOG.info("Created job via IPC: {}", job.id());
|
LoadLevel loadLevel;
|
||||||
|
if (loadLevelStr != null) {
|
||||||
|
loadLevel = LoadLevel.fromString(loadLevelStr);
|
||||||
|
LOG.debug("Using explicit load level: {}", loadLevel);
|
||||||
|
} else {
|
||||||
|
loadLevel = loadLevelClassifier.classify(command);
|
||||||
|
LOG.debug("Auto-classified command as load level: {}", loadLevel);
|
||||||
|
}
|
||||||
|
|
||||||
|
Job job = repository.create(command, tag, jobsConfig, loadLevel);
|
||||||
|
LOG.info("Created job via IPC: {} (level={})", job.id(), loadLevel);
|
||||||
return job;
|
return job;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,41 @@
|
|||||||
[
|
[
|
||||||
|
{
|
||||||
|
"name": "com.samsonmedia.barn.cli.VersionProvider",
|
||||||
|
"allDeclaredConstructors": true,
|
||||||
|
"allPublicConstructors": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "com.samsonmedia.barn.ipc.IpcMessage",
|
||||||
|
"allDeclaredConstructors": true,
|
||||||
|
"allPublicConstructors": true,
|
||||||
|
"allDeclaredMethods": true,
|
||||||
|
"allPublicMethods": true,
|
||||||
|
"allDeclaredFields": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "com.samsonmedia.barn.jobs.Job",
|
||||||
|
"allDeclaredConstructors": true,
|
||||||
|
"allPublicConstructors": true,
|
||||||
|
"allDeclaredMethods": true,
|
||||||
|
"allPublicMethods": true,
|
||||||
|
"allDeclaredFields": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "com.samsonmedia.barn.jobs.JobManifest",
|
||||||
|
"allDeclaredConstructors": true,
|
||||||
|
"allPublicConstructors": true,
|
||||||
|
"allDeclaredMethods": true,
|
||||||
|
"allPublicMethods": true,
|
||||||
|
"allDeclaredFields": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "com.samsonmedia.barn.state.JobState",
|
||||||
|
"allDeclaredConstructors": true,
|
||||||
|
"allPublicConstructors": true,
|
||||||
|
"allDeclaredMethods": true,
|
||||||
|
"allPublicMethods": true,
|
||||||
|
"allDeclaredFields": true
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"name": "ch.qos.logback.core.status.NopStatusListener",
|
"name": "ch.qos.logback.core.status.NopStatusListener",
|
||||||
"allDeclaredConstructors": true,
|
"allDeclaredConstructors": true,
|
||||||
|
|||||||
@@ -2,7 +2,9 @@
|
|||||||
"resources": {
|
"resources": {
|
||||||
"includes": [
|
"includes": [
|
||||||
{"pattern": "logback.xml"},
|
{"pattern": "logback.xml"},
|
||||||
{"pattern": "META-INF/.*"}
|
{"pattern": "version.properties"},
|
||||||
|
{"pattern": "META-INF/.*"},
|
||||||
|
{"pattern": "defaults/.*"}
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
"bundles": []
|
"bundles": []
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
# Barn Configuration
|
||||||
|
# Generated by: barn config install
|
||||||
|
|
||||||
|
[service]
|
||||||
|
# Logging verbosity: debug, info, warn, error
|
||||||
|
log_level = "info"
|
||||||
|
|
||||||
|
# DEPRECATED: Use [load_levels] section instead
|
||||||
|
# max_concurrent_jobs = 4
|
||||||
|
|
||||||
|
# How often running jobs update their heartbeat (seconds)
|
||||||
|
heartbeat_interval_seconds = 5
|
||||||
|
|
||||||
|
# Heartbeat age before a job is considered orphaned (seconds)
|
||||||
|
stale_heartbeat_threshold_seconds = 30
|
||||||
|
|
||||||
|
[load_levels]
|
||||||
|
# Maximum concurrent high load jobs (CPU/GPU intensive)
|
||||||
|
max_high_jobs = 2
|
||||||
|
|
||||||
|
# Maximum concurrent medium load jobs (general purpose)
|
||||||
|
max_medium_jobs = 8
|
||||||
|
|
||||||
|
# Maximum concurrent low load jobs (network/IO intensive)
|
||||||
|
max_low_jobs = 32
|
||||||
|
|
||||||
|
[jobs]
|
||||||
|
# Maximum time a job can run before being killed (seconds)
|
||||||
|
default_timeout_seconds = 3600
|
||||||
|
|
||||||
|
# Number of retry attempts for failed jobs
|
||||||
|
max_retries = 3
|
||||||
|
|
||||||
|
# Initial delay before first retry (seconds)
|
||||||
|
retry_delay_seconds = 30
|
||||||
|
|
||||||
|
# Multiplier applied to delay after each retry
|
||||||
|
retry_backoff_multiplier = 2.0
|
||||||
|
|
||||||
|
# Only retry on these exit codes (empty = retry all failures)
|
||||||
|
retry_on_exit_codes = []
|
||||||
|
|
||||||
|
[cleanup]
|
||||||
|
# Enable automatic cleanup of old jobs
|
||||||
|
enabled = true
|
||||||
|
|
||||||
|
# Remove jobs older than this (hours)
|
||||||
|
max_age_hours = 72
|
||||||
|
|
||||||
|
# How often the cleanup task runs (minutes)
|
||||||
|
cleanup_interval_minutes = 60
|
||||||
|
|
||||||
|
# Preserve failed jobs for debugging
|
||||||
|
keep_failed_jobs = true
|
||||||
|
|
||||||
|
# How long to keep failed jobs (hours)
|
||||||
|
keep_failed_jobs_hours = 168
|
||||||
|
|
||||||
|
[storage]
|
||||||
|
# Root directory for all Barn data
|
||||||
|
base_dir = "/tmp/barn"
|
||||||
|
|
||||||
|
# Maximum disk space Barn can use (GB)
|
||||||
|
max_disk_usage_gb = 50
|
||||||
|
|
||||||
|
# Keep work/input and work/output after job completion
|
||||||
|
preserve_work_dir = false
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# High load commands - CPU/GPU intensive (transcoding, encoding)
|
||||||
|
# Maximum concurrent: 2 (default)
|
||||||
|
#
|
||||||
|
# Format:
|
||||||
|
# - Binary name: ffmpeg (matches any path ending with this executable)
|
||||||
|
# - Full path: /usr/local/bin/ffmpeg
|
||||||
|
# - Directory: /opt/encoders/ (trailing slash = match any executable in this directory)
|
||||||
|
|
||||||
|
ffmpeg
|
||||||
|
ffprobe
|
||||||
|
handbrake
|
||||||
|
HandBrakeCLI
|
||||||
|
x264
|
||||||
|
x265
|
||||||
|
av1an
|
||||||
|
svt-av1
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
# Low load commands - Network/IO intensive (downloads, uploads)
|
||||||
|
# Maximum concurrent: 32 (default)
|
||||||
|
#
|
||||||
|
# Format:
|
||||||
|
# - Binary name: curl (matches any path ending with this executable)
|
||||||
|
# - Full path: /usr/local/bin/rclone
|
||||||
|
# - Directory: /opt/downloaders/ (trailing slash = match any executable in this directory)
|
||||||
|
|
||||||
|
curl
|
||||||
|
wget
|
||||||
|
rclone
|
||||||
|
rsync
|
||||||
|
aria2c
|
||||||
|
scp
|
||||||
|
sftp
|
||||||
|
cadaver
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
# Medium load commands
|
||||||
|
# Maximum concurrent: 8 (default)
|
||||||
|
#
|
||||||
|
# Empty by default - unmatched commands are classified as MEDIUM
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
version=${project.version}
|
||||||
@@ -112,11 +112,12 @@ class ConfigCommandTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void show_withNonExistentConfig_shouldShowDefaultsMessage() {
|
void show_withDefaults_shouldShowDefaultsIndicator() {
|
||||||
int exitCode = cmd.execute("config", "show");
|
// Using --defaults explicitly shows the default values indicator
|
||||||
|
int exitCode = cmd.execute("config", "show", "--defaults");
|
||||||
|
|
||||||
assertThat(exitCode).isZero();
|
assertThat(exitCode).isZero();
|
||||||
assertThat(outWriter.toString()).contains("(none found, using defaults)");
|
assertThat(outWriter.toString()).contains("Showing default values");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
package com.samsonmedia.barn.cli;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import java.io.PrintWriter;
|
||||||
|
import java.io.StringWriter;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Nested;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
import picocli.CommandLine;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests for ConfigInstallCommand.
|
||||||
|
*/
|
||||||
|
class ConfigInstallCommandTest {
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
private Path tempDir;
|
||||||
|
|
||||||
|
private StringWriter outWriter;
|
||||||
|
private StringWriter errWriter;
|
||||||
|
private CommandLine cmd;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
outWriter = new StringWriter();
|
||||||
|
errWriter = new StringWriter();
|
||||||
|
cmd = new CommandLine(new BarnCommand());
|
||||||
|
cmd.setOut(new PrintWriter(outWriter));
|
||||||
|
cmd.setErr(new PrintWriter(errWriter));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class InstallWithForce {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void install_withForce_shouldCreateAllFiles() {
|
||||||
|
Path targetDir = tempDir.resolve("barn-config");
|
||||||
|
|
||||||
|
int exitCode = cmd.execute("config", "install",
|
||||||
|
"--directory", targetDir.toString(),
|
||||||
|
"--force");
|
||||||
|
|
||||||
|
assertThat(exitCode).isZero();
|
||||||
|
assertThat(Files.exists(targetDir.resolve("barn.conf"))).isTrue();
|
||||||
|
assertThat(Files.exists(targetDir.resolve("high.load"))).isTrue();
|
||||||
|
assertThat(Files.exists(targetDir.resolve("medium.load"))).isTrue();
|
||||||
|
assertThat(Files.exists(targetDir.resolve("low.load"))).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void install_withForce_shouldCreateValidBarnConf() throws Exception {
|
||||||
|
Path targetDir = tempDir.resolve("barn-config");
|
||||||
|
|
||||||
|
cmd.execute("config", "install", "--directory", targetDir.toString(), "--force");
|
||||||
|
|
||||||
|
String content = Files.readString(targetDir.resolve("barn.conf"));
|
||||||
|
assertThat(content).contains("[service]");
|
||||||
|
assertThat(content).contains("[load_levels]");
|
||||||
|
assertThat(content).contains("[jobs]");
|
||||||
|
assertThat(content).contains("[cleanup]");
|
||||||
|
assertThat(content).contains("[storage]");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void install_withForce_shouldCreateValidHighLoad() throws Exception {
|
||||||
|
Path targetDir = tempDir.resolve("barn-config");
|
||||||
|
|
||||||
|
cmd.execute("config", "install", "--directory", targetDir.toString(), "--force");
|
||||||
|
|
||||||
|
String content = Files.readString(targetDir.resolve("high.load"));
|
||||||
|
assertThat(content).contains("ffmpeg");
|
||||||
|
assertThat(content).contains("x264");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void install_withForce_shouldCreateValidLowLoad() throws Exception {
|
||||||
|
Path targetDir = tempDir.resolve("barn-config");
|
||||||
|
|
||||||
|
cmd.execute("config", "install", "--directory", targetDir.toString(), "--force");
|
||||||
|
|
||||||
|
String content = Files.readString(targetDir.resolve("low.load"));
|
||||||
|
assertThat(content).contains("curl");
|
||||||
|
assertThat(content).contains("wget");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void install_withForce_shouldOverwriteExistingFiles() throws Exception {
|
||||||
|
Path targetDir = tempDir.resolve("barn-config");
|
||||||
|
Files.createDirectories(targetDir);
|
||||||
|
Files.writeString(targetDir.resolve("barn.conf"), "old content");
|
||||||
|
|
||||||
|
int exitCode = cmd.execute("config", "install",
|
||||||
|
"--directory", targetDir.toString(),
|
||||||
|
"--force");
|
||||||
|
|
||||||
|
assertThat(exitCode).isZero();
|
||||||
|
String content = Files.readString(targetDir.resolve("barn.conf"));
|
||||||
|
assertThat(content).contains("[service]");
|
||||||
|
assertThat(content).doesNotContain("old content");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class ShowOption {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void install_withShow_shouldNotWriteFiles() {
|
||||||
|
Path targetDir = tempDir.resolve("barn-config");
|
||||||
|
|
||||||
|
int exitCode = cmd.execute("config", "install",
|
||||||
|
"--directory", targetDir.toString(),
|
||||||
|
"--show");
|
||||||
|
|
||||||
|
assertThat(exitCode).isZero();
|
||||||
|
assertThat(Files.exists(targetDir)).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void install_withShow_shouldDisplayFileList() {
|
||||||
|
Path targetDir = tempDir.resolve("barn-config");
|
||||||
|
|
||||||
|
cmd.execute("config", "install",
|
||||||
|
"--directory", targetDir.toString(),
|
||||||
|
"--show");
|
||||||
|
|
||||||
|
String output = outWriter.toString();
|
||||||
|
assertThat(output).contains("barn.conf");
|
||||||
|
assertThat(output).contains("high.load");
|
||||||
|
assertThat(output).contains("medium.load");
|
||||||
|
assertThat(output).contains("low.load");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class HelpOption {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void install_withHelp_shouldShowUsage() {
|
||||||
|
int exitCode = cmd.execute("config", "install", "--help");
|
||||||
|
|
||||||
|
assertThat(exitCode).isZero();
|
||||||
|
assertThat(outWriter.toString()).contains("Install default configuration files");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.cli;
|
package com.samsonmedia.barn.cli;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
@@ -50,6 +51,8 @@ class HumanFormatterTest {
|
|||||||
assertThat(result).contains("Job: job-12345678");
|
assertThat(result).contains("Job: job-12345678");
|
||||||
assertThat(result).contains("State:");
|
assertThat(result).contains("State:");
|
||||||
assertThat(result).contains("running");
|
assertThat(result).contains("running");
|
||||||
|
assertThat(result).contains("Load:");
|
||||||
|
assertThat(result).contains("medium");
|
||||||
assertThat(result).contains("Tag:");
|
assertThat(result).contains("Tag:");
|
||||||
assertThat(result).contains("test-tag");
|
assertThat(result).contains("test-tag");
|
||||||
}
|
}
|
||||||
@@ -76,6 +79,18 @@ class HumanFormatterTest {
|
|||||||
assertThat(result).contains("Process failed");
|
assertThat(result).contains("Process failed");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void format_withRetryingJob_shouldShowRetryInfo() {
|
||||||
|
Job job = createRetryingJob("job-retry1234", 3,
|
||||||
|
Instant.parse("2026-01-15T10:30:00Z"));
|
||||||
|
|
||||||
|
String result = formatter.format(job);
|
||||||
|
|
||||||
|
assertThat(result).contains("Retries:");
|
||||||
|
assertThat(result).contains("3");
|
||||||
|
assertThat(result).contains("Retry At:");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void format_withMap_shouldFormatKeyValues() {
|
void format_withMap_shouldFormatKeyValues() {
|
||||||
Map<String, Object> map = new LinkedHashMap<>();
|
Map<String, Object> map = new LinkedHashMap<>();
|
||||||
@@ -115,11 +130,25 @@ class HumanFormatterTest {
|
|||||||
|
|
||||||
assertThat(result).contains("ID");
|
assertThat(result).contains("ID");
|
||||||
assertThat(result).contains("STATE");
|
assertThat(result).contains("STATE");
|
||||||
|
assertThat(result).contains("LOAD");
|
||||||
assertThat(result).contains("TAG");
|
assertThat(result).contains("TAG");
|
||||||
assertThat(result).contains("job-11111111");
|
assertThat(result).contains("job-11111111");
|
||||||
assertThat(result).contains("job-22222222");
|
assertThat(result).contains("job-22222222");
|
||||||
assertThat(result).contains("running");
|
assertThat(result).contains("running");
|
||||||
assertThat(result).contains("queued");
|
assertThat(result).contains("queued");
|
||||||
|
assertThat(result).contains("medium");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void formatList_withRetryingJob_shouldShowRetryColumns() {
|
||||||
|
List<Job> jobs = List.of(createRetryingJob("job-retry1234", 2,
|
||||||
|
Instant.parse("2026-01-15T10:30:00Z")));
|
||||||
|
|
||||||
|
String result = formatter.formatList(jobs);
|
||||||
|
|
||||||
|
assertThat(result).contains("RETRIES");
|
||||||
|
assertThat(result).contains("NEXT RETRY");
|
||||||
|
assertThat(result).contains("2");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -195,7 +224,8 @@ class HumanFormatterTest {
|
|||||||
state == JobState.RUNNING ? 12345L : null,
|
state == JobState.RUNNING ? 12345L : null,
|
||||||
null,
|
null,
|
||||||
0,
|
0,
|
||||||
null
|
null,
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -213,7 +243,8 @@ class HumanFormatterTest {
|
|||||||
null,
|
null,
|
||||||
null,
|
null,
|
||||||
0,
|
0,
|
||||||
null
|
null,
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -231,7 +262,27 @@ class HumanFormatterTest {
|
|||||||
null,
|
null,
|
||||||
null,
|
null,
|
||||||
0,
|
0,
|
||||||
null
|
null,
|
||||||
|
MEDIUM
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Job createRetryingJob(String id, int retryCount, Instant retryAt) {
|
||||||
|
return new Job(
|
||||||
|
id,
|
||||||
|
JobState.QUEUED,
|
||||||
|
List.of("echo", "test"),
|
||||||
|
"tag",
|
||||||
|
Instant.now().minus(Duration.ofMinutes(5)),
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
retryCount,
|
||||||
|
retryAt,
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.cli;
|
package com.samsonmedia.barn.cli;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
@@ -195,7 +196,8 @@ class JsonFormatterTest {
|
|||||||
state == JobState.RUNNING ? 12345L : null,
|
state == JobState.RUNNING ? 12345L : null,
|
||||||
null,
|
null,
|
||||||
0,
|
0,
|
||||||
null
|
null,
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -50,7 +50,8 @@ class ServiceInstallCommandTest {
|
|||||||
int exitCode = cmd.execute("service", "install", "--help");
|
int exitCode = cmd.execute("service", "install", "--help");
|
||||||
assertThat(exitCode).isEqualTo(0);
|
assertThat(exitCode).isEqualTo(0);
|
||||||
assertThat(stdout.toString()).contains("Install Barn as a system service");
|
assertThat(stdout.toString()).contains("Install Barn as a system service");
|
||||||
assertThat(stdout.toString()).contains("--user");
|
assertThat(stdout.toString()).contains("--binary");
|
||||||
|
assertThat(stdout.toString()).contains("--barn-dir");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -81,7 +82,6 @@ class ServiceInstallCommandTest {
|
|||||||
int exitCode = cmd.execute("service", "uninstall", "--help");
|
int exitCode = cmd.execute("service", "uninstall", "--help");
|
||||||
assertThat(exitCode).isEqualTo(0);
|
assertThat(exitCode).isEqualTo(0);
|
||||||
assertThat(stdout.toString()).contains("Uninstall Barn system service");
|
assertThat(stdout.toString()).contains("Uninstall Barn system service");
|
||||||
assertThat(stdout.toString()).contains("--user");
|
|
||||||
assertThat(stdout.toString()).contains("--force");
|
assertThat(stdout.toString()).contains("--force");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,8 @@ import java.io.IOException;
|
|||||||
import java.io.PrintWriter;
|
import java.io.PrintWriter;
|
||||||
import java.io.StringWriter;
|
import java.io.StringWriter;
|
||||||
import java.nio.file.Path;
|
import java.nio.file.Path;
|
||||||
|
import java.time.Instant;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
import org.junit.jupiter.api.BeforeEach;
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
@@ -14,6 +16,7 @@ import org.junit.jupiter.api.Test;
|
|||||||
import org.junit.jupiter.api.io.TempDir;
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
import com.samsonmedia.barn.config.JobsConfig;
|
import com.samsonmedia.barn.config.JobsConfig;
|
||||||
|
import com.samsonmedia.barn.jobs.Job;
|
||||||
import com.samsonmedia.barn.jobs.JobRepository;
|
import com.samsonmedia.barn.jobs.JobRepository;
|
||||||
import com.samsonmedia.barn.state.BarnDirectories;
|
import com.samsonmedia.barn.state.BarnDirectories;
|
||||||
|
|
||||||
@@ -100,6 +103,22 @@ class StatusCommandTest {
|
|||||||
assertThat(exitCode).isZero();
|
assertThat(exitCode).isZero();
|
||||||
assertThat(stdout.toString().toLowerCase()).contains("queued");
|
assertThat(stdout.toString().toLowerCase()).contains("queued");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void status_withRetryingJob_shouldShowRetryColumns() throws IOException {
|
||||||
|
Job job = repository.create(List.of("echo", "test"), "test", config);
|
||||||
|
repository.markStarted(job.id(), 12345L);
|
||||||
|
repository.markCompleted(job.id(), 1, "test failure");
|
||||||
|
Instant retryAt = Instant.now().plus(5, ChronoUnit.MINUTES);
|
||||||
|
repository.scheduleRetry(job.id(), retryAt);
|
||||||
|
|
||||||
|
int exitCode = cmd.execute("--offline");
|
||||||
|
|
||||||
|
assertThat(exitCode).isZero();
|
||||||
|
String output = stdout.toString();
|
||||||
|
assertThat(output).contains("RETRIES");
|
||||||
|
assertThat(output).contains("NEXT RETRY");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nested
|
@Nested
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.samsonmedia.barn.cli;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
class VersionProviderTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getVersion_shouldReturnVersionFromProperties() {
|
||||||
|
// Arrange
|
||||||
|
var provider = new VersionProvider();
|
||||||
|
|
||||||
|
// Act
|
||||||
|
String[] version = provider.getVersion();
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertThat(version).hasSize(1);
|
||||||
|
assertThat(version[0]).startsWith("barn ");
|
||||||
|
assertThat(version[0]).doesNotContain("unknown");
|
||||||
|
assertThat(version[0]).doesNotContain("${");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.cli;
|
package com.samsonmedia.barn.cli;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
|
||||||
import java.time.Duration;
|
import java.time.Duration;
|
||||||
@@ -191,8 +192,44 @@ class XmlFormatterTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class RetryFields {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void format_withRetryingJob_shouldIncludeRetryFields() {
|
||||||
|
Job job = createRetryingJob("job-retry1234", 2,
|
||||||
|
Instant.parse("2026-01-15T10:30:00Z"));
|
||||||
|
|
||||||
|
String result = formatter.format(job);
|
||||||
|
|
||||||
|
assertThat(result).contains("<retry_count>2</retry_count>");
|
||||||
|
assertThat(result).contains("<retry_at>");
|
||||||
|
assertThat(result).contains("2026-01-15T10:30:00Z");
|
||||||
|
assertThat(result).contains("</retry_at>");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// Helper methods
|
// Helper methods
|
||||||
|
|
||||||
|
private Job createRetryingJob(String id, int retryCount, Instant retryAt) {
|
||||||
|
return new Job(
|
||||||
|
id,
|
||||||
|
JobState.QUEUED,
|
||||||
|
List.of("echo", "test"),
|
||||||
|
"tag",
|
||||||
|
Instant.now(),
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
null,
|
||||||
|
retryCount,
|
||||||
|
retryAt,
|
||||||
|
MEDIUM
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
private Job createJob(String id, JobState state, String tag) {
|
private Job createJob(String id, JobState state, String tag) {
|
||||||
return new Job(
|
return new Job(
|
||||||
id,
|
id,
|
||||||
@@ -207,7 +244,8 @@ class XmlFormatterTest {
|
|||||||
state == JobState.RUNNING ? 12345L : null,
|
state == JobState.RUNNING ? 12345L : null,
|
||||||
null,
|
null,
|
||||||
0,
|
0,
|
||||||
null
|
null,
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
package com.samsonmedia.barn.config;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Nested;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests for CommandMatcher sealed interface and implementations.
|
||||||
|
*/
|
||||||
|
class CommandMatcherTest {
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class ExecutableNameMatcherTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withMatchingExecutableName_shouldReturnTrue() {
|
||||||
|
var matcher = new CommandMatcher.ExecutableName("ffmpeg");
|
||||||
|
|
||||||
|
assertThat(matcher.matches(List.of("ffmpeg", "-i", "input.mp4"))).isTrue();
|
||||||
|
assertThat(matcher.matches(List.of("/usr/bin/ffmpeg", "-i", "input.mp4"))).isTrue();
|
||||||
|
assertThat(matcher.matches(List.of("/opt/local/bin/ffmpeg", "-version"))).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withNonMatchingExecutableName_shouldReturnFalse() {
|
||||||
|
var matcher = new CommandMatcher.ExecutableName("ffmpeg");
|
||||||
|
|
||||||
|
assertThat(matcher.matches(List.of("curl", "http://example.com"))).isFalse();
|
||||||
|
assertThat(matcher.matches(List.of("/usr/bin/curl", "-O", "file"))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withPartialMatch_shouldReturnFalse() {
|
||||||
|
var matcher = new CommandMatcher.ExecutableName("ffmpeg");
|
||||||
|
|
||||||
|
// ffmpegXXX should not match
|
||||||
|
assertThat(matcher.matches(List.of("ffmpegXXX", "-i", "input.mp4"))).isFalse();
|
||||||
|
// prefix should not match
|
||||||
|
assertThat(matcher.matches(List.of("/usr/bin/ffmpegXXX", "-version"))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withEmptyCommand_shouldReturnFalse() {
|
||||||
|
var matcher = new CommandMatcher.ExecutableName("ffmpeg");
|
||||||
|
|
||||||
|
assertThat(matcher.matches(List.of())).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withNull_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new CommandMatcher.ExecutableName(null))
|
||||||
|
.isInstanceOf(NullPointerException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withBlank_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new CommandMatcher.ExecutableName(" "))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class FullPathMatcherTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withExactPath_shouldReturnTrue() {
|
||||||
|
var matcher = new CommandMatcher.FullPath(Path.of("/usr/local/bin/ffmpeg"));
|
||||||
|
|
||||||
|
assertThat(matcher.matches(List.of("/usr/local/bin/ffmpeg", "-i", "input.mp4"))).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withDifferentPath_shouldReturnFalse() {
|
||||||
|
var matcher = new CommandMatcher.FullPath(Path.of("/usr/local/bin/ffmpeg"));
|
||||||
|
|
||||||
|
assertThat(matcher.matches(List.of("/usr/bin/ffmpeg", "-i", "input.mp4"))).isFalse();
|
||||||
|
assertThat(matcher.matches(List.of("ffmpeg", "-i", "input.mp4"))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withEmptyCommand_shouldReturnFalse() {
|
||||||
|
var matcher = new CommandMatcher.FullPath(Path.of("/usr/local/bin/ffmpeg"));
|
||||||
|
|
||||||
|
assertThat(matcher.matches(List.of())).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withNull_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new CommandMatcher.FullPath(null))
|
||||||
|
.isInstanceOf(NullPointerException.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class DirectoryMatcherTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withCommandInDirectory_shouldReturnTrue() {
|
||||||
|
var matcher = new CommandMatcher.Directory(Path.of("/opt/encoders/"));
|
||||||
|
|
||||||
|
assertThat(matcher.matches(List.of("/opt/encoders/x264", "-i", "input.mp4"))).isTrue();
|
||||||
|
assertThat(matcher.matches(List.of("/opt/encoders/x265", "-o", "output.mp4"))).isTrue();
|
||||||
|
assertThat(matcher.matches(List.of("/opt/encoders/av1an", "-i", "input.mp4"))).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withCommandNotInDirectory_shouldReturnFalse() {
|
||||||
|
var matcher = new CommandMatcher.Directory(Path.of("/opt/encoders/"));
|
||||||
|
|
||||||
|
assertThat(matcher.matches(List.of("/usr/bin/ffmpeg", "-i", "input.mp4"))).isFalse();
|
||||||
|
assertThat(matcher.matches(List.of("ffmpeg", "-i", "input.mp4"))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withSubdirectory_shouldReturnFalse() {
|
||||||
|
var matcher = new CommandMatcher.Directory(Path.of("/opt/encoders/"));
|
||||||
|
|
||||||
|
// Subdirectories should not match
|
||||||
|
assertThat(matcher.matches(List.of("/opt/encoders/subdir/ffmpeg", "-version"))).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void matches_withEmptyCommand_shouldReturnFalse() {
|
||||||
|
var matcher = new CommandMatcher.Directory(Path.of("/opt/encoders/"));
|
||||||
|
|
||||||
|
assertThat(matcher.matches(List.of())).isFalse();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withNull_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new CommandMatcher.Directory(null))
|
||||||
|
.isInstanceOf(NullPointerException.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -287,6 +287,51 @@ class ConfigLoaderTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class LoadLevelsConfig {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void load_withLoadLevels_shouldParseValues() throws IOException {
|
||||||
|
Path configFile = tempDir.resolve("barn.conf");
|
||||||
|
Files.writeString(configFile, """
|
||||||
|
[load_levels]
|
||||||
|
max_high_jobs = 4
|
||||||
|
max_medium_jobs = 16
|
||||||
|
max_low_jobs = 64
|
||||||
|
""");
|
||||||
|
|
||||||
|
ConfigLoader loader = new ConfigLoader(Map.of());
|
||||||
|
Config config = loader.loadFromFile(configFile);
|
||||||
|
|
||||||
|
assertThat(config.loadLevels().maxHighJobs()).isEqualTo(4);
|
||||||
|
assertThat(config.loadLevels().maxMediumJobs()).isEqualTo(16);
|
||||||
|
assertThat(config.loadLevels().maxLowJobs()).isEqualTo(64);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void load_withNoLoadLevels_shouldUseDefaults() {
|
||||||
|
ConfigLoader loader = new ConfigLoader(Map.of());
|
||||||
|
Config config = loader.load();
|
||||||
|
|
||||||
|
assertThat(config.loadLevels().maxHighJobs()).isEqualTo(2);
|
||||||
|
assertThat(config.loadLevels().maxMediumJobs()).isEqualTo(8);
|
||||||
|
assertThat(config.loadLevels().maxLowJobs()).isEqualTo(32);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void load_withEnvOverride_shouldOverrideLoadLevelValues() {
|
||||||
|
// Environment variables use BARN_LOADLEVELS_ (no underscore) because
|
||||||
|
// the parser splits on first underscore for section name
|
||||||
|
Map<String, String> env = new HashMap<>();
|
||||||
|
env.put("BARN_LOADLEVELS_MAX_HIGH_JOBS", "10");
|
||||||
|
|
||||||
|
ConfigLoader loader = new ConfigLoader(env);
|
||||||
|
Config config = loader.load();
|
||||||
|
|
||||||
|
assertThat(config.loadLevels().maxHighJobs()).isEqualTo(10);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Nested
|
@Nested
|
||||||
class RetryOnExitCodes {
|
class RetryOnExitCodes {
|
||||||
|
|
||||||
|
|||||||
@@ -222,13 +222,15 @@ class ConfigTest {
|
|||||||
ServiceConfig.withDefaults(),
|
ServiceConfig.withDefaults(),
|
||||||
JobsConfig.withDefaults(),
|
JobsConfig.withDefaults(),
|
||||||
CleanupConfig.withDefaults(),
|
CleanupConfig.withDefaults(),
|
||||||
StorageConfig.withDefaults()
|
StorageConfig.withDefaults(),
|
||||||
|
LoadLevelConfig.withDefaults()
|
||||||
);
|
);
|
||||||
|
|
||||||
assertThat(config.service()).isNotNull();
|
assertThat(config.service()).isNotNull();
|
||||||
assertThat(config.jobs()).isNotNull();
|
assertThat(config.jobs()).isNotNull();
|
||||||
assertThat(config.cleanup()).isNotNull();
|
assertThat(config.cleanup()).isNotNull();
|
||||||
assertThat(config.storage()).isNotNull();
|
assertThat(config.storage()).isNotNull();
|
||||||
|
assertThat(config.loadLevels()).isNotNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -237,7 +239,8 @@ class ConfigTest {
|
|||||||
null,
|
null,
|
||||||
JobsConfig.withDefaults(),
|
JobsConfig.withDefaults(),
|
||||||
CleanupConfig.withDefaults(),
|
CleanupConfig.withDefaults(),
|
||||||
StorageConfig.withDefaults()))
|
StorageConfig.withDefaults(),
|
||||||
|
LoadLevelConfig.withDefaults()))
|
||||||
.isInstanceOf(NullPointerException.class)
|
.isInstanceOf(NullPointerException.class)
|
||||||
.hasMessageContaining("service");
|
.hasMessageContaining("service");
|
||||||
}
|
}
|
||||||
@@ -248,11 +251,24 @@ class ConfigTest {
|
|||||||
ServiceConfig.withDefaults(),
|
ServiceConfig.withDefaults(),
|
||||||
null,
|
null,
|
||||||
CleanupConfig.withDefaults(),
|
CleanupConfig.withDefaults(),
|
||||||
StorageConfig.withDefaults()))
|
StorageConfig.withDefaults(),
|
||||||
|
LoadLevelConfig.withDefaults()))
|
||||||
.isInstanceOf(NullPointerException.class)
|
.isInstanceOf(NullPointerException.class)
|
||||||
.hasMessageContaining("jobs");
|
.hasMessageContaining("jobs");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withNullLoadLevels_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new Config(
|
||||||
|
ServiceConfig.withDefaults(),
|
||||||
|
JobsConfig.withDefaults(),
|
||||||
|
CleanupConfig.withDefaults(),
|
||||||
|
StorageConfig.withDefaults(),
|
||||||
|
null))
|
||||||
|
.isInstanceOf(NullPointerException.class)
|
||||||
|
.hasMessageContaining("loadLevels");
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void withDefaults_shouldReturnFullyPopulatedConfig() {
|
void withDefaults_shouldReturnFullyPopulatedConfig() {
|
||||||
Config config = Config.withDefaults();
|
Config config = Config.withDefaults();
|
||||||
@@ -261,6 +277,7 @@ class ConfigTest {
|
|||||||
assertThat(config.jobs()).isNotNull();
|
assertThat(config.jobs()).isNotNull();
|
||||||
assertThat(config.cleanup()).isNotNull();
|
assertThat(config.cleanup()).isNotNull();
|
||||||
assertThat(config.storage()).isNotNull();
|
assertThat(config.storage()).isNotNull();
|
||||||
|
assertThat(config.loadLevels()).isNotNull();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
package com.samsonmedia.barn.config;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests for LoadFileParser.
|
||||||
|
*/
|
||||||
|
class LoadFileParserTest {
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
private Path tempDir;
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withEmptyFile_shouldReturnEmptyList() throws IOException {
|
||||||
|
Path loadFile = tempDir.resolve("empty.load");
|
||||||
|
Files.writeString(loadFile, "");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parse(loadFile);
|
||||||
|
|
||||||
|
assertThat(matchers).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withOnlyComments_shouldReturnEmptyList() throws IOException {
|
||||||
|
Path loadFile = tempDir.resolve("comments.load");
|
||||||
|
Files.writeString(loadFile, """
|
||||||
|
# This is a comment
|
||||||
|
# Another comment
|
||||||
|
""");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parse(loadFile);
|
||||||
|
|
||||||
|
assertThat(matchers).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withOnlyBlankLines_shouldReturnEmptyList() throws IOException {
|
||||||
|
Path loadFile = tempDir.resolve("blank.load");
|
||||||
|
Files.writeString(loadFile, """
|
||||||
|
|
||||||
|
\s\s
|
||||||
|
\t
|
||||||
|
""");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parse(loadFile);
|
||||||
|
|
||||||
|
assertThat(matchers).isEmpty();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withExecutableNames_shouldReturnExecutableNameMatchers() throws IOException {
|
||||||
|
Path loadFile = tempDir.resolve("executables.load");
|
||||||
|
Files.writeString(loadFile, """
|
||||||
|
ffmpeg
|
||||||
|
ffprobe
|
||||||
|
handbrake
|
||||||
|
""");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parse(loadFile);
|
||||||
|
|
||||||
|
assertThat(matchers).hasSize(3);
|
||||||
|
assertThat(matchers.get(0)).isInstanceOf(CommandMatcher.ExecutableName.class);
|
||||||
|
assertThat(matchers.get(1)).isInstanceOf(CommandMatcher.ExecutableName.class);
|
||||||
|
assertThat(matchers.get(2)).isInstanceOf(CommandMatcher.ExecutableName.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withFullPaths_shouldReturnFullPathMatchers() throws IOException {
|
||||||
|
Path loadFile = tempDir.resolve("paths.load");
|
||||||
|
Files.writeString(loadFile, """
|
||||||
|
/usr/local/bin/ffmpeg
|
||||||
|
/opt/media/encoders/x264
|
||||||
|
""");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parse(loadFile);
|
||||||
|
|
||||||
|
assertThat(matchers).hasSize(2);
|
||||||
|
assertThat(matchers.get(0)).isInstanceOf(CommandMatcher.FullPath.class);
|
||||||
|
assertThat(matchers.get(1)).isInstanceOf(CommandMatcher.FullPath.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withDirectoryPaths_shouldReturnDirectoryMatchers() throws IOException {
|
||||||
|
Path loadFile = tempDir.resolve("dirs.load");
|
||||||
|
Files.writeString(loadFile, """
|
||||||
|
/opt/encoders/
|
||||||
|
/usr/local/media/
|
||||||
|
""");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parse(loadFile);
|
||||||
|
|
||||||
|
assertThat(matchers).hasSize(2);
|
||||||
|
assertThat(matchers.get(0)).isInstanceOf(CommandMatcher.Directory.class);
|
||||||
|
assertThat(matchers.get(1)).isInstanceOf(CommandMatcher.Directory.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withMixedEntries_shouldReturnCorrectMatchers() throws IOException {
|
||||||
|
Path loadFile = tempDir.resolve("mixed.load");
|
||||||
|
Files.writeString(loadFile, """
|
||||||
|
# High load commands
|
||||||
|
ffmpeg
|
||||||
|
/usr/local/bin/custom-encoder
|
||||||
|
/opt/encoders/
|
||||||
|
|
||||||
|
# More commands
|
||||||
|
handbrake
|
||||||
|
""");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parse(loadFile);
|
||||||
|
|
||||||
|
assertThat(matchers).hasSize(4);
|
||||||
|
assertThat(matchers.get(0)).isInstanceOf(CommandMatcher.ExecutableName.class);
|
||||||
|
assertThat(matchers.get(1)).isInstanceOf(CommandMatcher.FullPath.class);
|
||||||
|
assertThat(matchers.get(2)).isInstanceOf(CommandMatcher.Directory.class);
|
||||||
|
assertThat(matchers.get(3)).isInstanceOf(CommandMatcher.ExecutableName.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withNonExistentFile_shouldThrowIOException() {
|
||||||
|
Path nonExistent = tempDir.resolve("nonexistent.load");
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> LoadFileParser.parse(nonExistent))
|
||||||
|
.isInstanceOf(IOException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withNullPath_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> LoadFileParser.parse(null))
|
||||||
|
.isInstanceOf(NullPointerException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parse_withWhitespaceAroundEntries_shouldTrimEntries() throws IOException {
|
||||||
|
Path loadFile = tempDir.resolve("whitespace.load");
|
||||||
|
Files.writeString(loadFile, """
|
||||||
|
ffmpeg \s
|
||||||
|
\t curl\t
|
||||||
|
""");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parse(loadFile);
|
||||||
|
|
||||||
|
assertThat(matchers).hasSize(2);
|
||||||
|
assertThat(matchers.get(0).matches(List.of("ffmpeg", "-version"))).isTrue();
|
||||||
|
assertThat(matchers.get(1).matches(List.of("curl", "--help"))).isTrue();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parseIfExists_withExistingFile_shouldReturnMatchers() throws IOException {
|
||||||
|
Path loadFile = tempDir.resolve("existing.load");
|
||||||
|
Files.writeString(loadFile, "ffmpeg\n");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parseIfExists(loadFile);
|
||||||
|
|
||||||
|
assertThat(matchers).hasSize(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void parseIfExists_withNonExistentFile_shouldReturnEmptyList() {
|
||||||
|
Path nonExistent = tempDir.resolve("nonexistent.load");
|
||||||
|
|
||||||
|
List<CommandMatcher> matchers = LoadFileParser.parseIfExists(nonExistent);
|
||||||
|
|
||||||
|
assertThat(matchers).isEmpty();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
package com.samsonmedia.barn.config;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
import com.samsonmedia.barn.jobs.LoadLevel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests for LoadLevelConfig record.
|
||||||
|
*/
|
||||||
|
class LoadLevelConfigTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withValidValues_shouldCreateConfig() {
|
||||||
|
var config = new LoadLevelConfig(4, 16, 64);
|
||||||
|
|
||||||
|
assertThat(config.maxHighJobs()).isEqualTo(4);
|
||||||
|
assertThat(config.maxMediumJobs()).isEqualTo(16);
|
||||||
|
assertThat(config.maxLowJobs()).isEqualTo(64);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withZeroHighJobs_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new LoadLevelConfig(0, 8, 32))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessageContaining("maxHighJobs must be at least 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withNegativeHighJobs_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new LoadLevelConfig(-1, 8, 32))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessageContaining("maxHighJobs must be at least 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withZeroMediumJobs_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new LoadLevelConfig(2, 0, 32))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessageContaining("maxMediumJobs must be at least 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withZeroLowJobs_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new LoadLevelConfig(2, 8, 0))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessageContaining("maxLowJobs must be at least 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void withDefaults_shouldReturnDefaultValues() {
|
||||||
|
var config = LoadLevelConfig.withDefaults();
|
||||||
|
|
||||||
|
assertThat(config.maxHighJobs()).isEqualTo(LoadLevelConfig.DEFAULT_MAX_HIGH_JOBS);
|
||||||
|
assertThat(config.maxMediumJobs()).isEqualTo(LoadLevelConfig.DEFAULT_MAX_MEDIUM_JOBS);
|
||||||
|
assertThat(config.maxLowJobs()).isEqualTo(LoadLevelConfig.DEFAULT_MAX_LOW_JOBS);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void defaultConstants_shouldMatchLoadLevelDefaults() {
|
||||||
|
assertThat(LoadLevelConfig.DEFAULT_MAX_HIGH_JOBS).isEqualTo(LoadLevel.HIGH.getDefaultMaxJobs());
|
||||||
|
assertThat(LoadLevelConfig.DEFAULT_MAX_MEDIUM_JOBS).isEqualTo(LoadLevel.MEDIUM.getDefaultMaxJobs());
|
||||||
|
assertThat(LoadLevelConfig.DEFAULT_MAX_LOW_JOBS).isEqualTo(LoadLevel.LOW.getDefaultMaxJobs());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getMaxJobsFor_shouldReturnCorrectLimit() {
|
||||||
|
var config = new LoadLevelConfig(4, 16, 64);
|
||||||
|
|
||||||
|
assertThat(config.getMaxJobsFor(LoadLevel.HIGH)).isEqualTo(4);
|
||||||
|
assertThat(config.getMaxJobsFor(LoadLevel.MEDIUM)).isEqualTo(16);
|
||||||
|
assertThat(config.getMaxJobsFor(LoadLevel.LOW)).isEqualTo(64);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getMaxJobsFor_withNull_shouldThrowException() {
|
||||||
|
var config = LoadLevelConfig.withDefaults();
|
||||||
|
|
||||||
|
assertThatThrownBy(() -> config.getMaxJobsFor(null))
|
||||||
|
.isInstanceOf(NullPointerException.class)
|
||||||
|
.hasMessageContaining("level must not be null");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getTotalMaxJobs_shouldReturnSum() {
|
||||||
|
var config = new LoadLevelConfig(4, 16, 64);
|
||||||
|
|
||||||
|
assertThat(config.getTotalMaxJobs()).isEqualTo(84);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.execution;
|
package com.samsonmedia.barn.execution;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
@@ -212,7 +213,8 @@ class CrashRecoveryTest {
|
|||||||
config.service(),
|
config.service(),
|
||||||
new JobsConfig(config.jobs().defaultTimeoutSeconds(), 0, 1, 1.0, List.of()),
|
new JobsConfig(config.jobs().defaultTimeoutSeconds(), 0, 1, 1.0, List.of()),
|
||||||
config.cleanup(),
|
config.cleanup(),
|
||||||
config.storage()
|
config.storage(),
|
||||||
|
config.loadLevels()
|
||||||
);
|
);
|
||||||
CrashRecovery noRetryCrashRecovery = new CrashRecovery(
|
CrashRecovery noRetryCrashRecovery = new CrashRecovery(
|
||||||
repository, heartbeatChecker, dirs, noRetryConfig);
|
repository, heartbeatChecker, dirs, noRetryConfig);
|
||||||
@@ -296,7 +298,8 @@ class CrashRecoveryTest {
|
|||||||
pid,
|
pid,
|
||||||
heartbeat,
|
heartbeat,
|
||||||
0, // retryCount
|
0, // retryCount
|
||||||
null // retryAt
|
null, // retryAt
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.execution;
|
package com.samsonmedia.barn.execution;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
@@ -161,7 +162,8 @@ class HeartbeatCheckerTest {
|
|||||||
state == JobState.RUNNING ? 12345L : null, // pid
|
state == JobState.RUNNING ? 12345L : null, // pid
|
||||||
heartbeat,
|
heartbeat,
|
||||||
0, // retryCount
|
0, // retryCount
|
||||||
null // retryAt
|
null, // retryAt
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -15,6 +15,7 @@ import org.junit.jupiter.api.Test;
|
|||||||
import org.junit.jupiter.api.io.TempDir;
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
import com.samsonmedia.barn.config.JobsConfig;
|
import com.samsonmedia.barn.config.JobsConfig;
|
||||||
|
import com.samsonmedia.barn.config.LoadLevelConfig;
|
||||||
import com.samsonmedia.barn.jobs.Job;
|
import com.samsonmedia.barn.jobs.Job;
|
||||||
import com.samsonmedia.barn.jobs.JobRepository;
|
import com.samsonmedia.barn.jobs.JobRepository;
|
||||||
import com.samsonmedia.barn.state.BarnDirectories;
|
import com.samsonmedia.barn.state.BarnDirectories;
|
||||||
@@ -189,13 +190,15 @@ class JobSchedulerTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void getStatus_whenNotRunning_shouldShowNotRunning() {
|
void getStatus_whenNotRunning_shouldShowNotRunning() {
|
||||||
|
// Legacy constructor with maxConcurrentJobs=2 creates config with 1 HIGH + 2 MEDIUM + 1 LOW = 4 total
|
||||||
scheduler = new JobScheduler(repository, runner, dirs, 2,
|
scheduler = new JobScheduler(repository, runner, dirs, 2,
|
||||||
Duration.ofMillis(100), Duration.ofSeconds(5));
|
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||||
|
|
||||||
JobScheduler.SchedulerStatus status = scheduler.getStatus();
|
JobScheduler.SchedulerStatus status = scheduler.getStatus();
|
||||||
|
|
||||||
assertThat(status.isRunning()).isFalse();
|
assertThat(status.isRunning()).isFalse();
|
||||||
assertThat(status.maxConcurrentJobs()).isEqualTo(2);
|
assertThat(status.maxConcurrentJobs()).isEqualTo(4); // 1 + 2 + 1
|
||||||
|
assertThat(status.maxMediumJobs()).isEqualTo(2); // The configured value
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -279,6 +282,56 @@ class JobSchedulerTest {
|
|||||||
assertThat(status.maxConcurrentJobs()).isEqualTo(8);
|
assertThat(status.maxConcurrentJobs()).isEqualTo(8);
|
||||||
assertThat(status.isRunning()).isTrue();
|
assertThat(status.isRunning()).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void schedulerStatus_withPerLevelFields_shouldContainAllFields() {
|
||||||
|
JobScheduler.SchedulerStatus status = new JobScheduler.SchedulerStatus(
|
||||||
|
10, 5, 42, true, 2, 5, 3, 4, 8, 30);
|
||||||
|
|
||||||
|
assertThat(status.runningJobs()).isEqualTo(10);
|
||||||
|
assertThat(status.queuedJobs()).isEqualTo(5);
|
||||||
|
assertThat(status.maxConcurrentJobs()).isEqualTo(42);
|
||||||
|
assertThat(status.isRunning()).isTrue();
|
||||||
|
assertThat(status.runningHighJobs()).isEqualTo(2);
|
||||||
|
assertThat(status.runningMediumJobs()).isEqualTo(5);
|
||||||
|
assertThat(status.runningLowJobs()).isEqualTo(3);
|
||||||
|
assertThat(status.maxHighJobs()).isEqualTo(4);
|
||||||
|
assertThat(status.maxMediumJobs()).isEqualTo(8);
|
||||||
|
assertThat(status.maxLowJobs()).isEqualTo(30);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class PerLevelScheduling {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withLoadLevelConfig_shouldUsePerLevelLimits() throws IOException {
|
||||||
|
LoadLevelConfig levelConfig = new LoadLevelConfig(2, 4, 8);
|
||||||
|
scheduler = new JobScheduler(repository, runner, dirs, levelConfig,
|
||||||
|
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||||
|
|
||||||
|
JobScheduler.SchedulerStatus status = scheduler.getStatus();
|
||||||
|
|
||||||
|
assertThat(status.maxHighJobs()).isEqualTo(2);
|
||||||
|
assertThat(status.maxMediumJobs()).isEqualTo(4);
|
||||||
|
assertThat(status.maxLowJobs()).isEqualTo(8);
|
||||||
|
assertThat(status.maxConcurrentJobs()).isEqualTo(14); // 2 + 4 + 8
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getStatus_shouldReportPerLevelRunningCounts() throws IOException {
|
||||||
|
LoadLevelConfig levelConfig = new LoadLevelConfig(2, 4, 8);
|
||||||
|
scheduler = new JobScheduler(repository, runner, dirs, levelConfig,
|
||||||
|
Duration.ofMillis(100), Duration.ofSeconds(5));
|
||||||
|
|
||||||
|
JobScheduler.SchedulerStatus status = scheduler.getStatus();
|
||||||
|
|
||||||
|
// Initially no jobs are running
|
||||||
|
assertThat(status.runningHighJobs()).isZero();
|
||||||
|
assertThat(status.runningMediumJobs()).isZero();
|
||||||
|
assertThat(status.runningLowJobs()).isZero();
|
||||||
|
assertThat(status.runningJobs()).isZero();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Helper methods
|
// Helper methods
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.jobs;
|
package com.samsonmedia.barn.jobs;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
@@ -23,7 +24,7 @@ class JobManifestTest {
|
|||||||
List.of("echo", "hello"),
|
List.of("echo", "hello"),
|
||||||
"test-tag",
|
"test-tag",
|
||||||
now,
|
now,
|
||||||
3, 30, 2.0
|
3, 30, 2.0, MEDIUM
|
||||||
);
|
);
|
||||||
|
|
||||||
assertThat(manifest.id()).isEqualTo("job-12345");
|
assertThat(manifest.id()).isEqualTo("job-12345");
|
||||||
@@ -38,7 +39,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void constructor_withNullId_shouldThrowException() {
|
void constructor_withNullId_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new JobManifest(
|
assertThatThrownBy(() -> new JobManifest(
|
||||||
null, List.of("echo"), null, Instant.now(), 3, 30, 2.0))
|
null, List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM))
|
||||||
.isInstanceOf(NullPointerException.class)
|
.isInstanceOf(NullPointerException.class)
|
||||||
.hasMessageContaining("id");
|
.hasMessageContaining("id");
|
||||||
}
|
}
|
||||||
@@ -46,7 +47,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void constructor_withBlankId_shouldThrowException() {
|
void constructor_withBlankId_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new JobManifest(
|
assertThatThrownBy(() -> new JobManifest(
|
||||||
" ", List.of("echo"), null, Instant.now(), 3, 30, 2.0))
|
" ", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM))
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessageContaining("blank");
|
.hasMessageContaining("blank");
|
||||||
}
|
}
|
||||||
@@ -54,7 +55,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void constructor_withEmptyCommand_shouldThrowException() {
|
void constructor_withEmptyCommand_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new JobManifest(
|
assertThatThrownBy(() -> new JobManifest(
|
||||||
"job-12345", List.of(), null, Instant.now(), 3, 30, 2.0))
|
"job-12345", List.of(), null, Instant.now(), 3, 30, 2.0, MEDIUM))
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessageContaining("empty");
|
.hasMessageContaining("empty");
|
||||||
}
|
}
|
||||||
@@ -62,7 +63,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void constructor_withNegativeMaxRetries_shouldThrowException() {
|
void constructor_withNegativeMaxRetries_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new JobManifest(
|
assertThatThrownBy(() -> new JobManifest(
|
||||||
"job-12345", List.of("echo"), null, Instant.now(), -1, 30, 2.0))
|
"job-12345", List.of("echo"), null, Instant.now(), -1, 30, 2.0, MEDIUM))
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessageContaining("maxRetries");
|
.hasMessageContaining("maxRetries");
|
||||||
}
|
}
|
||||||
@@ -70,7 +71,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void constructor_withNegativeRetryDelay_shouldThrowException() {
|
void constructor_withNegativeRetryDelay_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new JobManifest(
|
assertThatThrownBy(() -> new JobManifest(
|
||||||
"job-12345", List.of("echo"), null, Instant.now(), 3, -1, 2.0))
|
"job-12345", List.of("echo"), null, Instant.now(), 3, -1, 2.0, MEDIUM))
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessageContaining("retryDelaySeconds");
|
.hasMessageContaining("retryDelaySeconds");
|
||||||
}
|
}
|
||||||
@@ -78,7 +79,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void constructor_withBackoffMultiplierLessThanOne_shouldThrowException() {
|
void constructor_withBackoffMultiplierLessThanOne_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new JobManifest(
|
assertThatThrownBy(() -> new JobManifest(
|
||||||
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 0.5))
|
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 0.5, MEDIUM))
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessageContaining("retryBackoffMultiplier");
|
.hasMessageContaining("retryBackoffMultiplier");
|
||||||
}
|
}
|
||||||
@@ -107,7 +108,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void calculateRetryDelay_shouldUseExponentialBackoff() {
|
void calculateRetryDelay_shouldUseExponentialBackoff() {
|
||||||
JobManifest manifest = new JobManifest(
|
JobManifest manifest = new JobManifest(
|
||||||
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0);
|
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM);
|
||||||
|
|
||||||
assertThat(manifest.calculateRetryDelay(0)).isEqualTo(30); // 30 * 2^0
|
assertThat(manifest.calculateRetryDelay(0)).isEqualTo(30); // 30 * 2^0
|
||||||
assertThat(manifest.calculateRetryDelay(1)).isEqualTo(60); // 30 * 2^1
|
assertThat(manifest.calculateRetryDelay(1)).isEqualTo(60); // 30 * 2^1
|
||||||
@@ -117,7 +118,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void calculateRetryDelay_withNegativeCount_shouldThrowException() {
|
void calculateRetryDelay_withNegativeCount_shouldThrowException() {
|
||||||
JobManifest manifest = new JobManifest(
|
JobManifest manifest = new JobManifest(
|
||||||
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0);
|
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM);
|
||||||
|
|
||||||
assertThatThrownBy(() -> manifest.calculateRetryDelay(-1))
|
assertThatThrownBy(() -> manifest.calculateRetryDelay(-1))
|
||||||
.isInstanceOf(IllegalArgumentException.class);
|
.isInstanceOf(IllegalArgumentException.class);
|
||||||
@@ -126,7 +127,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void canRetry_withRetriesAvailable_shouldReturnTrue() {
|
void canRetry_withRetriesAvailable_shouldReturnTrue() {
|
||||||
JobManifest manifest = new JobManifest(
|
JobManifest manifest = new JobManifest(
|
||||||
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0);
|
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM);
|
||||||
|
|
||||||
assertThat(manifest.canRetry(0)).isTrue();
|
assertThat(manifest.canRetry(0)).isTrue();
|
||||||
assertThat(manifest.canRetry(1)).isTrue();
|
assertThat(manifest.canRetry(1)).isTrue();
|
||||||
@@ -136,7 +137,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void canRetry_withNoRetriesLeft_shouldReturnFalse() {
|
void canRetry_withNoRetriesLeft_shouldReturnFalse() {
|
||||||
JobManifest manifest = new JobManifest(
|
JobManifest manifest = new JobManifest(
|
||||||
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0);
|
"job-12345", List.of("echo"), null, Instant.now(), 3, 30, 2.0, MEDIUM);
|
||||||
|
|
||||||
assertThat(manifest.canRetry(3)).isFalse();
|
assertThat(manifest.canRetry(3)).isFalse();
|
||||||
assertThat(manifest.canRetry(4)).isFalse();
|
assertThat(manifest.canRetry(4)).isFalse();
|
||||||
@@ -145,7 +146,7 @@ class JobManifestTest {
|
|||||||
@Test
|
@Test
|
||||||
void canRetry_withZeroMaxRetries_shouldAlwaysReturnFalse() {
|
void canRetry_withZeroMaxRetries_shouldAlwaysReturnFalse() {
|
||||||
JobManifest manifest = new JobManifest(
|
JobManifest manifest = new JobManifest(
|
||||||
"job-12345", List.of("echo"), null, Instant.now(), 0, 30, 2.0);
|
"job-12345", List.of("echo"), null, Instant.now(), 0, 30, 2.0, MEDIUM);
|
||||||
|
|
||||||
assertThat(manifest.canRetry(0)).isFalse();
|
assertThat(manifest.canRetry(0)).isFalse();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -83,6 +83,39 @@ class JobRepositoryTest {
|
|||||||
|
|
||||||
assertThat(job.tag()).isNull();
|
assertThat(job.tag()).isNull();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_shouldDefaultToMediumLoadLevel() throws IOException {
|
||||||
|
Job job = repository.create(List.of("echo"), null, config);
|
||||||
|
|
||||||
|
assertThat(job.loadLevel()).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_withLoadLevel_shouldUseSpecifiedLevel() throws IOException {
|
||||||
|
Job job = repository.create(List.of("ffmpeg", "-version"), null, config, LoadLevel.HIGH);
|
||||||
|
|
||||||
|
assertThat(job.loadLevel()).isEqualTo(LoadLevel.HIGH);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_withLoadLevel_shouldPersistInManifest() throws IOException {
|
||||||
|
Job job = repository.create(List.of("curl", "-h"), null, config, LoadLevel.LOW);
|
||||||
|
|
||||||
|
Path manifestPath = dirs.getJobDir(job.id()).resolve("manifest.json");
|
||||||
|
String content = Files.readString(manifestPath);
|
||||||
|
assertThat(content).contains("\"loadLevel\" : \"LOW\"");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void create_withLoadLevel_shouldBeReadableByFindById() throws IOException {
|
||||||
|
Job created = repository.create(List.of("wget"), null, config, LoadLevel.LOW);
|
||||||
|
|
||||||
|
Optional<Job> found = repository.findById(created.id());
|
||||||
|
|
||||||
|
assertThat(found).isPresent();
|
||||||
|
assertThat(found.get().loadLevel()).isEqualTo(LoadLevel.LOW);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nested
|
@Nested
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.jobs;
|
package com.samsonmedia.barn.jobs;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
@@ -23,7 +24,7 @@ class JobTest {
|
|||||||
List.of("echo", "hello"),
|
List.of("echo", "hello"),
|
||||||
"test-tag",
|
"test-tag",
|
||||||
Instant.now(),
|
Instant.now(),
|
||||||
null, null, null, null, null, null, 0, null
|
null, null, null, null, null, null, 0, null, MEDIUM
|
||||||
);
|
);
|
||||||
|
|
||||||
assertThat(job.id()).isEqualTo("job-12345");
|
assertThat(job.id()).isEqualTo("job-12345");
|
||||||
@@ -36,7 +37,7 @@ class JobTest {
|
|||||||
void constructor_withNullId_shouldThrowException() {
|
void constructor_withNullId_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new Job(
|
assertThatThrownBy(() -> new Job(
|
||||||
null, JobState.QUEUED, List.of("echo"), null,
|
null, JobState.QUEUED, List.of("echo"), null,
|
||||||
Instant.now(), null, null, null, null, null, null, 0, null))
|
Instant.now(), null, null, null, null, null, null, 0, null, MEDIUM))
|
||||||
.isInstanceOf(NullPointerException.class)
|
.isInstanceOf(NullPointerException.class)
|
||||||
.hasMessageContaining("id");
|
.hasMessageContaining("id");
|
||||||
}
|
}
|
||||||
@@ -45,7 +46,7 @@ class JobTest {
|
|||||||
void constructor_withBlankId_shouldThrowException() {
|
void constructor_withBlankId_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new Job(
|
assertThatThrownBy(() -> new Job(
|
||||||
" ", JobState.QUEUED, List.of("echo"), null,
|
" ", JobState.QUEUED, List.of("echo"), null,
|
||||||
Instant.now(), null, null, null, null, null, null, 0, null))
|
Instant.now(), null, null, null, null, null, null, 0, null, MEDIUM))
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessageContaining("blank");
|
.hasMessageContaining("blank");
|
||||||
}
|
}
|
||||||
@@ -54,7 +55,7 @@ class JobTest {
|
|||||||
void constructor_withNullState_shouldThrowException() {
|
void constructor_withNullState_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new Job(
|
assertThatThrownBy(() -> new Job(
|
||||||
"job-12345", null, List.of("echo"), null,
|
"job-12345", null, List.of("echo"), null,
|
||||||
Instant.now(), null, null, null, null, null, null, 0, null))
|
Instant.now(), null, null, null, null, null, null, 0, null, MEDIUM))
|
||||||
.isInstanceOf(NullPointerException.class)
|
.isInstanceOf(NullPointerException.class)
|
||||||
.hasMessageContaining("state");
|
.hasMessageContaining("state");
|
||||||
}
|
}
|
||||||
@@ -63,7 +64,7 @@ class JobTest {
|
|||||||
void constructor_withEmptyCommand_shouldThrowException() {
|
void constructor_withEmptyCommand_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new Job(
|
assertThatThrownBy(() -> new Job(
|
||||||
"job-12345", JobState.QUEUED, List.of(), null,
|
"job-12345", JobState.QUEUED, List.of(), null,
|
||||||
Instant.now(), null, null, null, null, null, null, 0, null))
|
Instant.now(), null, null, null, null, null, null, 0, null, MEDIUM))
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessageContaining("empty");
|
.hasMessageContaining("empty");
|
||||||
}
|
}
|
||||||
@@ -72,7 +73,7 @@ class JobTest {
|
|||||||
void constructor_withNegativeRetryCount_shouldThrowException() {
|
void constructor_withNegativeRetryCount_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new Job(
|
assertThatThrownBy(() -> new Job(
|
||||||
"job-12345", JobState.QUEUED, List.of("echo"), null,
|
"job-12345", JobState.QUEUED, List.of("echo"), null,
|
||||||
Instant.now(), null, null, null, null, null, null, -1, null))
|
Instant.now(), null, null, null, null, null, null, -1, null, MEDIUM))
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessageContaining("retryCount");
|
.hasMessageContaining("retryCount");
|
||||||
}
|
}
|
||||||
@@ -231,4 +232,29 @@ class JobTest {
|
|||||||
assertThat(queued.isQueued()).isTrue();
|
assertThat(queued.isQueued()).isTrue();
|
||||||
assertThat(running.isQueued()).isFalse();
|
assertThat(running.isQueued()).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void createQueued_shouldDefaultToMediumLoadLevel() {
|
||||||
|
Job job = Job.createQueued("job-12345", List.of("echo", "test"), "my-tag");
|
||||||
|
|
||||||
|
assertThat(job.loadLevel()).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void createQueued_withLoadLevel_shouldUseSpecifiedLevel() {
|
||||||
|
Job job = Job.createQueued("job-12345", List.of("ffmpeg", "-i", "input.mp4"),
|
||||||
|
"transcode", LoadLevel.HIGH);
|
||||||
|
|
||||||
|
assertThat(job.loadLevel()).isEqualTo(LoadLevel.HIGH);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void withLoadLevel_shouldCreateCopyWithNewLoadLevel() {
|
||||||
|
Job original = Job.createQueued("job-12345", List.of("echo"), null);
|
||||||
|
|
||||||
|
Job updated = original.withLoadLevel(LoadLevel.LOW);
|
||||||
|
|
||||||
|
assertThat(updated.loadLevel()).isEqualTo(LoadLevel.LOW);
|
||||||
|
assertThat(original.loadLevel()).isEqualTo(LoadLevel.MEDIUM); // Original unchanged
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,149 @@
|
|||||||
|
package com.samsonmedia.barn.jobs;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import java.io.IOException;
|
||||||
|
import java.nio.file.Files;
|
||||||
|
import java.nio.file.Path;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.Nested;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.junit.jupiter.api.io.TempDir;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests for LoadLevelClassifier.
|
||||||
|
*/
|
||||||
|
class LoadLevelClassifierTest {
|
||||||
|
|
||||||
|
@TempDir
|
||||||
|
private Path tempDir;
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class ClassificationTests {
|
||||||
|
|
||||||
|
private LoadLevelClassifier classifier;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() throws IOException {
|
||||||
|
// Create high.load with ffmpeg, x264
|
||||||
|
Files.writeString(tempDir.resolve("high.load"), """
|
||||||
|
# High load commands
|
||||||
|
ffmpeg
|
||||||
|
x264
|
||||||
|
/usr/local/bin/handbrake
|
||||||
|
""");
|
||||||
|
|
||||||
|
// Create empty medium.load
|
||||||
|
Files.writeString(tempDir.resolve("medium.load"), """
|
||||||
|
# Medium load - empty by default
|
||||||
|
""");
|
||||||
|
|
||||||
|
// Create low.load with curl, wget
|
||||||
|
Files.writeString(tempDir.resolve("low.load"), """
|
||||||
|
# Low load commands
|
||||||
|
curl
|
||||||
|
wget
|
||||||
|
rclone
|
||||||
|
""");
|
||||||
|
|
||||||
|
classifier = LoadLevelClassifier.load(tempDir);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void classify_withHighLoadCommand_shouldReturnHigh() {
|
||||||
|
assertThat(classifier.classify(List.of("ffmpeg", "-i", "input.mp4"))).isEqualTo(LoadLevel.HIGH);
|
||||||
|
assertThat(classifier.classify(List.of("/usr/bin/ffmpeg", "-version"))).isEqualTo(LoadLevel.HIGH);
|
||||||
|
assertThat(classifier.classify(List.of("x264", "--preset", "slow"))).isEqualTo(LoadLevel.HIGH);
|
||||||
|
assertThat(classifier.classify(List.of("/usr/local/bin/handbrake", "-i", "input"))).isEqualTo(LoadLevel.HIGH);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void classify_withLowLoadCommand_shouldReturnLow() {
|
||||||
|
assertThat(classifier.classify(List.of("curl", "http://example.com"))).isEqualTo(LoadLevel.LOW);
|
||||||
|
assertThat(classifier.classify(List.of("/usr/bin/wget", "-O", "file"))).isEqualTo(LoadLevel.LOW);
|
||||||
|
assertThat(classifier.classify(List.of("rclone", "sync", "source:", "dest:"))).isEqualTo(LoadLevel.LOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void classify_withUnknownCommand_shouldReturnMedium() {
|
||||||
|
assertThat(classifier.classify(List.of("echo", "hello"))).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
assertThat(classifier.classify(List.of("/bin/bash", "-c", "ls"))).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
assertThat(classifier.classify(List.of("python3", "script.py"))).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void classify_withEmptyCommand_shouldReturnMedium() {
|
||||||
|
assertThat(classifier.classify(List.of())).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void classify_withNull_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> classifier.classify(null))
|
||||||
|
.isInstanceOf(NullPointerException.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class LoadingTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void load_withAllFilesPresent_shouldLoadAllMatchers() throws IOException {
|
||||||
|
Files.writeString(tempDir.resolve("high.load"), "ffmpeg\n");
|
||||||
|
Files.writeString(tempDir.resolve("medium.load"), "custom-tool\n");
|
||||||
|
Files.writeString(tempDir.resolve("low.load"), "curl\n");
|
||||||
|
|
||||||
|
LoadLevelClassifier classifier = LoadLevelClassifier.load(tempDir);
|
||||||
|
|
||||||
|
assertThat(classifier.classify(List.of("ffmpeg"))).isEqualTo(LoadLevel.HIGH);
|
||||||
|
assertThat(classifier.classify(List.of("custom-tool"))).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
assertThat(classifier.classify(List.of("curl"))).isEqualTo(LoadLevel.LOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void load_withMissingFiles_shouldTreatAsEmpty() throws IOException {
|
||||||
|
// No load files exist
|
||||||
|
|
||||||
|
LoadLevelClassifier classifier = LoadLevelClassifier.load(tempDir);
|
||||||
|
|
||||||
|
// Everything should default to MEDIUM
|
||||||
|
assertThat(classifier.classify(List.of("ffmpeg"))).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
assertThat(classifier.classify(List.of("curl"))).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void load_withNullPath_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> LoadLevelClassifier.load(null))
|
||||||
|
.isInstanceOf(NullPointerException.class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class PriorityTests {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void classify_whenInMultipleLists_shouldPrioritizeHighOverLow() throws IOException {
|
||||||
|
// Put ffmpeg in both high and low
|
||||||
|
Files.writeString(tempDir.resolve("high.load"), "ffmpeg\n");
|
||||||
|
Files.writeString(tempDir.resolve("low.load"), "ffmpeg\n");
|
||||||
|
|
||||||
|
LoadLevelClassifier classifier = LoadLevelClassifier.load(tempDir);
|
||||||
|
|
||||||
|
// HIGH should win
|
||||||
|
assertThat(classifier.classify(List.of("ffmpeg"))).isEqualTo(LoadLevel.HIGH);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void classify_whenInMediumAndLow_shouldPrioritizeMediumOverLow() throws IOException {
|
||||||
|
Files.writeString(tempDir.resolve("medium.load"), "curl\n");
|
||||||
|
Files.writeString(tempDir.resolve("low.load"), "curl\n");
|
||||||
|
|
||||||
|
LoadLevelClassifier classifier = LoadLevelClassifier.load(tempDir);
|
||||||
|
|
||||||
|
// MEDIUM should win over LOW
|
||||||
|
assertThat(classifier.classify(List.of("curl"))).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,90 @@
|
|||||||
|
package com.samsonmedia.barn.jobs;
|
||||||
|
|
||||||
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tests for LoadLevel enum.
|
||||||
|
*/
|
||||||
|
class LoadLevelTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void values_shouldContainAllLoadLevels() {
|
||||||
|
assertThat(LoadLevel.values()).containsExactly(
|
||||||
|
LoadLevel.HIGH,
|
||||||
|
LoadLevel.MEDIUM,
|
||||||
|
LoadLevel.LOW
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fromString_withValidLowercase_shouldReturnLoadLevel() {
|
||||||
|
assertThat(LoadLevel.fromString("high")).isEqualTo(LoadLevel.HIGH);
|
||||||
|
assertThat(LoadLevel.fromString("medium")).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
assertThat(LoadLevel.fromString("low")).isEqualTo(LoadLevel.LOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fromString_withValidUppercase_shouldReturnLoadLevel() {
|
||||||
|
assertThat(LoadLevel.fromString("HIGH")).isEqualTo(LoadLevel.HIGH);
|
||||||
|
assertThat(LoadLevel.fromString("MEDIUM")).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
assertThat(LoadLevel.fromString("LOW")).isEqualTo(LoadLevel.LOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fromString_withMixedCase_shouldReturnLoadLevel() {
|
||||||
|
assertThat(LoadLevel.fromString("High")).isEqualTo(LoadLevel.HIGH);
|
||||||
|
assertThat(LoadLevel.fromString("Medium")).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
assertThat(LoadLevel.fromString("Low")).isEqualTo(LoadLevel.LOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fromString_withWhitespace_shouldTrimAndParse() {
|
||||||
|
assertThat(LoadLevel.fromString(" high ")).isEqualTo(LoadLevel.HIGH);
|
||||||
|
assertThat(LoadLevel.fromString(" medium ")).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fromString_withNull_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> LoadLevel.fromString(null))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessageContaining("cannot be null or blank");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fromString_withBlank_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> LoadLevel.fromString(" "))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessageContaining("cannot be null or blank");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void fromString_withInvalidValue_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> LoadLevel.fromString("invalid"))
|
||||||
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
|
.hasMessageContaining("Invalid load level")
|
||||||
|
.hasMessageContaining("invalid")
|
||||||
|
.hasMessageContaining("high, medium, low");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void toLowercase_shouldReturnLowercaseString() {
|
||||||
|
assertThat(LoadLevel.HIGH.toLowercase()).isEqualTo("high");
|
||||||
|
assertThat(LoadLevel.MEDIUM.toLowercase()).isEqualTo("medium");
|
||||||
|
assertThat(LoadLevel.LOW.toLowercase()).isEqualTo("low");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getDefaultMaxJobs_shouldReturnCorrectDefaults() {
|
||||||
|
assertThat(LoadLevel.HIGH.getDefaultMaxJobs()).isEqualTo(2);
|
||||||
|
assertThat(LoadLevel.MEDIUM.getDefaultMaxJobs()).isEqualTo(8);
|
||||||
|
assertThat(LoadLevel.LOW.getDefaultMaxJobs()).isEqualTo(32);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void getDefault_shouldReturnMedium() {
|
||||||
|
assertThat(LoadLevel.getDefault()).isEqualTo(LoadLevel.MEDIUM);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.jobs;
|
package com.samsonmedia.barn.jobs;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
@@ -260,7 +261,8 @@ class RetryCalculatorTest {
|
|||||||
12345L,
|
12345L,
|
||||||
Instant.now(),
|
Instant.now(),
|
||||||
retryCount,
|
retryCount,
|
||||||
null
|
null,
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -278,7 +280,8 @@ class RetryCalculatorTest {
|
|||||||
12345L,
|
12345L,
|
||||||
Instant.now(),
|
Instant.now(),
|
||||||
retryCount,
|
retryCount,
|
||||||
null
|
null,
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.logging;
|
package com.samsonmedia.barn.logging;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThat;
|
import static org.assertj.core.api.Assertions.assertThat;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
@@ -183,7 +184,8 @@ class JobContextTest {
|
|||||||
null, // pid
|
null, // pid
|
||||||
null, // heartbeat
|
null, // heartbeat
|
||||||
0, // retryCount
|
0, // retryCount
|
||||||
null // retryAt
|
null, // retryAt
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
package com.samsonmedia.barn.logging;
|
package com.samsonmedia.barn.logging;
|
||||||
|
|
||||||
|
import static com.samsonmedia.barn.jobs.LoadLevel.MEDIUM;
|
||||||
import static org.assertj.core.api.Assertions.assertThatCode;
|
import static org.assertj.core.api.Assertions.assertThatCode;
|
||||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||||
|
|
||||||
@@ -200,7 +201,8 @@ class JobLogEventsTest {
|
|||||||
null, // pid
|
null, // pid
|
||||||
null, // heartbeat
|
null, // heartbeat
|
||||||
0, // retryCount
|
0, // retryCount
|
||||||
null // retryAt
|
null, // retryAt
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -218,7 +220,8 @@ class JobLogEventsTest {
|
|||||||
pid,
|
pid,
|
||||||
Instant.now(), // heartbeat
|
Instant.now(), // heartbeat
|
||||||
0, // retryCount
|
0, // retryCount
|
||||||
null // retryAt
|
null, // retryAt
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -236,7 +239,8 @@ class JobLogEventsTest {
|
|||||||
null, // pid
|
null, // pid
|
||||||
null, // heartbeat
|
null, // heartbeat
|
||||||
0, // retryCount
|
0, // retryCount
|
||||||
null // retryAt
|
null, // retryAt
|
||||||
|
MEDIUM
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -14,6 +14,7 @@ import org.junit.jupiter.api.io.TempDir;
|
|||||||
import com.samsonmedia.barn.config.CleanupConfig;
|
import com.samsonmedia.barn.config.CleanupConfig;
|
||||||
import com.samsonmedia.barn.config.Config;
|
import com.samsonmedia.barn.config.Config;
|
||||||
import com.samsonmedia.barn.config.JobsConfig;
|
import com.samsonmedia.barn.config.JobsConfig;
|
||||||
|
import com.samsonmedia.barn.config.LoadLevelConfig;
|
||||||
import com.samsonmedia.barn.config.LogLevel;
|
import com.samsonmedia.barn.config.LogLevel;
|
||||||
import com.samsonmedia.barn.config.ServiceConfig;
|
import com.samsonmedia.barn.config.ServiceConfig;
|
||||||
import com.samsonmedia.barn.config.StorageConfig;
|
import com.samsonmedia.barn.config.StorageConfig;
|
||||||
@@ -45,7 +46,8 @@ class BarnServiceTest {
|
|||||||
CleanupConfig cleanupConfig = new CleanupConfig(false, 60, 24, false, 168);
|
CleanupConfig cleanupConfig = new CleanupConfig(false, 60, 24, false, 168);
|
||||||
StorageConfig storageConfig = new StorageConfig(tempDir, 50, false);
|
StorageConfig storageConfig = new StorageConfig(tempDir, 50, false);
|
||||||
|
|
||||||
config = new Config(serviceConfig, jobsConfig, cleanupConfig, storageConfig);
|
config = new Config(serviceConfig, jobsConfig, cleanupConfig, storageConfig,
|
||||||
|
LoadLevelConfig.withDefaults());
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
|
|||||||
Reference in new issue
Block a user