Archived
Compare commits
5
Commits
v0.1.2-rc1
...
v0.1.2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8ded382831 | ||
|
|
f916fc2f8b | ||
|
|
27648a03a8 | ||
|
|
ccabf9d4c1 | ||
|
|
7b45fce813 |
No files matched your search
@@ -48,12 +48,28 @@ jobs:
|
|||||||
Move-Item -Path "target\barn.exe" -Destination "target\${{ matrix.artifact }}.exe" -Force
|
Move-Item -Path "target\barn.exe" -Destination "target\${{ matrix.artifact }}.exe" -Force
|
||||||
Get-ChildItem target\*.exe
|
Get-ChildItem target\*.exe
|
||||||
|
|
||||||
|
- name: Build Windows installer
|
||||||
|
if: runner.os == 'Windows'
|
||||||
|
shell: pwsh
|
||||||
|
run: |
|
||||||
|
$version = "${{ github.ref_name }}" -replace '^v', ''
|
||||||
|
choco install innosetup -y
|
||||||
|
iscc /DAppVersion=$version installer\barn.iss
|
||||||
|
Get-ChildItem dist\*.exe
|
||||||
|
|
||||||
- name: Upload artifact
|
- name: Upload artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
name: ${{ matrix.artifact }}
|
name: ${{ matrix.artifact }}
|
||||||
path: target/${{ matrix.artifact }}*
|
path: target/${{ matrix.artifact }}*
|
||||||
|
|
||||||
|
- name: Upload Windows installer
|
||||||
|
if: runner.os == 'Windows'
|
||||||
|
uses: actions/upload-artifact@v4
|
||||||
|
with:
|
||||||
|
name: windows-installer
|
||||||
|
path: dist/*.exe
|
||||||
|
|
||||||
release:
|
release:
|
||||||
needs: build-native
|
needs: build-native
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -69,6 +85,9 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
mkdir release
|
mkdir release
|
||||||
find artifacts -type f -exec mv {} release/ \;
|
find artifacts -type f -exec mv {} release/ \;
|
||||||
|
# Add installer scripts
|
||||||
|
cp install.sh release/
|
||||||
|
cp install.ps1 release/
|
||||||
cd release
|
cd release
|
||||||
sha256sum * > SHA256SUMS
|
sha256sum * > SHA256SUMS
|
||||||
ls -la
|
ls -la
|
||||||
|
|||||||
@@ -610,6 +610,174 @@ 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
|
## Questions to Ask Before Implementing
|
||||||
|
|
||||||
1. Have I read the relevant documentation?
|
1. Have I read the relevant documentation?
|
||||||
|
|||||||
@@ -42,57 +42,92 @@ This project treats FFmpeg jobs as **first-class managed units of work**, not sh
|
|||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
### macOS
|
### Quick Install (Recommended)
|
||||||
|
|
||||||
|
The installer scripts download the latest release, install the binary, and set up barn to run as a service on startup.
|
||||||
|
|
||||||
|
**macOS / Linux:**
|
||||||
|
```bash
|
||||||
|
curl -fsSL https://raw.githubusercontent.com/samson-media/barn/main/install.sh | sh
|
||||||
|
```
|
||||||
|
|
||||||
|
**Windows (PowerShell as Administrator):**
|
||||||
|
```powershell
|
||||||
|
iwr -useb https://raw.githubusercontent.com/samson-media/barn/main/install.ps1 | iex
|
||||||
|
```
|
||||||
|
|
||||||
|
**Windows Installer (setup.exe):**
|
||||||
|
|
||||||
|
Download the latest `setup-barn-vX.X.X-windows-x64.exe` from the [releases page](https://github.com/samson-media/barn/releases/latest).
|
||||||
|
|
||||||
|
### Alternative Installation Methods
|
||||||
|
|
||||||
|
#### macOS - Homebrew
|
||||||
|
|
||||||
**Homebrew (recommended):**
|
|
||||||
```bash
|
```bash
|
||||||
brew install samson-media/tap/barn
|
brew install samson-media/tap/barn
|
||||||
```
|
```
|
||||||
|
|
||||||
**Manual download:**
|
#### Manual Download
|
||||||
|
|
||||||
|
**macOS (ARM64):**
|
||||||
```bash
|
```bash
|
||||||
curl -L -o barn https://github.com/samson-media/barn/releases/latest/download/barn-macos-arm64
|
curl -L -o barn https://github.com/samson-media/barn/releases/latest/download/barn-macos-arm64
|
||||||
chmod +x barn
|
chmod +x barn
|
||||||
sudo mv barn /usr/local/bin/
|
sudo mv barn /usr/local/bin/
|
||||||
```
|
```
|
||||||
|
|
||||||
### Linux
|
**Linux (x64):**
|
||||||
|
|
||||||
**Download the binary:**
|
|
||||||
```bash
|
```bash
|
||||||
# For x64
|
|
||||||
curl -L -o barn https://github.com/samson-media/barn/releases/latest/download/barn-linux-x64
|
curl -L -o barn https://github.com/samson-media/barn/releases/latest/download/barn-linux-x64
|
||||||
|
|
||||||
# For ARM64
|
|
||||||
curl -L -o barn https://github.com/samson-media/barn/releases/latest/download/barn-linux-arm64
|
|
||||||
|
|
||||||
chmod +x barn
|
chmod +x barn
|
||||||
sudo mv barn /usr/local/bin/
|
sudo mv barn /usr/local/bin/
|
||||||
```
|
```
|
||||||
|
|
||||||
### Windows
|
**Linux (ARM64):**
|
||||||
|
```bash
|
||||||
|
curl -L -o barn https://github.com/samson-media/barn/releases/latest/download/barn-linux-arm64
|
||||||
|
chmod +x barn
|
||||||
|
sudo mv barn /usr/local/bin/
|
||||||
|
```
|
||||||
|
|
||||||
**PowerShell (recommended):**
|
**Windows (PowerShell):**
|
||||||
```powershell
|
```powershell
|
||||||
# Create install directory
|
|
||||||
New-Item -ItemType Directory -Force -Path "$env:LOCALAPPDATA\Programs\barn"
|
New-Item -ItemType Directory -Force -Path "$env:LOCALAPPDATA\Programs\barn"
|
||||||
|
|
||||||
# Download
|
|
||||||
Invoke-WebRequest -Uri "https://github.com/samson-media/barn/releases/latest/download/barn-windows-x64.exe" -OutFile "$env:LOCALAPPDATA\Programs\barn\barn.exe"
|
Invoke-WebRequest -Uri "https://github.com/samson-media/barn/releases/latest/download/barn-windows-x64.exe" -OutFile "$env:LOCALAPPDATA\Programs\barn\barn.exe"
|
||||||
|
|
||||||
# Add to PATH (current user)
|
|
||||||
$path = [Environment]::GetEnvironmentVariable("Path", "User")
|
$path = [Environment]::GetEnvironmentVariable("Path", "User")
|
||||||
if ($path -notlike "*$env:LOCALAPPDATA\Programs\barn*") {
|
if ($path -notlike "*$env:LOCALAPPDATA\Programs\barn*") {
|
||||||
[Environment]::SetEnvironmentVariable("Path", "$path;$env:LOCALAPPDATA\Programs\barn", "User")
|
[Environment]::SetEnvironmentVariable("Path", "$path;$env:LOCALAPPDATA\Programs\barn", "User")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
Restart your terminal after installation.
|
### Setting Up the Service (Manual Install)
|
||||||
|
|
||||||
|
If you installed manually, you need to set up the service to run on startup:
|
||||||
|
|
||||||
|
**Linux (systemd):**
|
||||||
|
```bash
|
||||||
|
barn service install
|
||||||
|
sudo systemctl enable barn
|
||||||
|
sudo systemctl start barn
|
||||||
|
```
|
||||||
|
|
||||||
|
**macOS (launchd):**
|
||||||
|
```bash
|
||||||
|
barn service install
|
||||||
|
```
|
||||||
|
|
||||||
|
**Windows (as Administrator):**
|
||||||
|
```powershell
|
||||||
|
barn service install
|
||||||
|
barn service start
|
||||||
|
```
|
||||||
|
|
||||||
### Verify Installation
|
### Verify Installation
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
barn --version
|
barn --version
|
||||||
|
barn service status
|
||||||
```
|
```
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
+269
@@ -0,0 +1,269 @@
|
|||||||
|
# Barn Installer Script for Windows
|
||||||
|
# Usage: iwr -useb https://raw.githubusercontent.com/samson-media/barn/main/install.ps1 | iex
|
||||||
|
#
|
||||||
|
# This script installs the Barn job daemon and sets it up to run on startup.
|
||||||
|
# Requires: PowerShell 5.1+ and Administrator privileges (for Windows Service)
|
||||||
|
|
||||||
|
param(
|
||||||
|
[switch]$NoService,
|
||||||
|
[string]$InstallDir = "$env:ProgramFiles\barn",
|
||||||
|
[string]$BarnDir = "$env:LOCALAPPDATA\barn"
|
||||||
|
)
|
||||||
|
|
||||||
|
$ErrorActionPreference = "Stop"
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
$Repo = "samson-media/barn"
|
||||||
|
$ServiceName = "barn"
|
||||||
|
$ServiceDisplayName = "Barn Job Daemon"
|
||||||
|
|
||||||
|
function Write-Info {
|
||||||
|
param([string]$Message)
|
||||||
|
Write-Host "[INFO] " -ForegroundColor Green -NoNewline
|
||||||
|
Write-Host $Message
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-Warn {
|
||||||
|
param([string]$Message)
|
||||||
|
Write-Host "[WARN] " -ForegroundColor Yellow -NoNewline
|
||||||
|
Write-Host $Message
|
||||||
|
}
|
||||||
|
|
||||||
|
function Write-Err {
|
||||||
|
param([string]$Message)
|
||||||
|
Write-Host "[ERROR] " -ForegroundColor Red -NoNewline
|
||||||
|
Write-Host $Message
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
function Test-Administrator {
|
||||||
|
$currentUser = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||||
|
$principal = New-Object Security.Principal.WindowsPrincipal($currentUser)
|
||||||
|
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
|
||||||
|
}
|
||||||
|
|
||||||
|
function Get-LatestVersion {
|
||||||
|
Write-Info "Getting latest version..."
|
||||||
|
try {
|
||||||
|
$release = Invoke-RestMethod -Uri "https://api.github.com/repos/$Repo/releases/latest"
|
||||||
|
$version = $release.tag_name
|
||||||
|
Write-Info "Latest version: $version"
|
||||||
|
return $version
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
Write-Err "Failed to get latest version: $_"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Install-Binary {
|
||||||
|
param([string]$Version)
|
||||||
|
|
||||||
|
$binaryName = "barn-windows-x64.exe"
|
||||||
|
$downloadUrl = "https://github.com/$Repo/releases/download/$Version/$binaryName"
|
||||||
|
|
||||||
|
Write-Info "Downloading $binaryName..."
|
||||||
|
|
||||||
|
# Create install directory
|
||||||
|
if (-not (Test-Path $InstallDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $InstallDir -Force | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
$destPath = Join-Path $InstallDir "barn.exe"
|
||||||
|
|
||||||
|
try {
|
||||||
|
# Download with progress
|
||||||
|
$ProgressPreference = 'SilentlyContinue'
|
||||||
|
Invoke-WebRequest -Uri $downloadUrl -OutFile $destPath -UseBasicParsing
|
||||||
|
$ProgressPreference = 'Continue'
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
Write-Err "Failed to download binary: $_"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Verify it works
|
||||||
|
try {
|
||||||
|
$versionOutput = & $destPath --version 2>&1
|
||||||
|
Write-Info "Installed: $versionOutput"
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
Write-Err "Downloaded binary is not executable or corrupted"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Info "Installed barn to $destPath"
|
||||||
|
return $destPath
|
||||||
|
}
|
||||||
|
|
||||||
|
function Add-ToPath {
|
||||||
|
param([string]$Directory)
|
||||||
|
|
||||||
|
$currentPath = [Environment]::GetEnvironmentVariable("Path", "Machine")
|
||||||
|
if ($currentPath -notlike "*$Directory*") {
|
||||||
|
Write-Info "Adding $Directory to system PATH..."
|
||||||
|
$newPath = "$currentPath;$Directory"
|
||||||
|
[Environment]::SetEnvironmentVariable("Path", $newPath, "Machine")
|
||||||
|
$env:Path = "$env:Path;$Directory"
|
||||||
|
Write-Info "Added to PATH. You may need to restart your terminal."
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Write-Info "$Directory is already in PATH"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Install-WindowsService {
|
||||||
|
param([string]$BinaryPath)
|
||||||
|
|
||||||
|
Write-Info "Setting up Windows Service..."
|
||||||
|
|
||||||
|
# Create barn data directory
|
||||||
|
if (-not (Test-Path $BarnDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $BarnDir -Force | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
# Check if service already exists
|
||||||
|
$existingService = Get-Service -Name $ServiceName -ErrorAction SilentlyContinue
|
||||||
|
if ($existingService) {
|
||||||
|
Write-Info "Stopping existing service..."
|
||||||
|
Stop-Service -Name $ServiceName -Force -ErrorAction SilentlyContinue
|
||||||
|
Write-Info "Removing existing service..."
|
||||||
|
sc.exe delete $ServiceName | Out-Null
|
||||||
|
Start-Sleep -Seconds 2
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create the service using sc.exe
|
||||||
|
$binPath = "`"$BinaryPath`" service start --foreground --barn-dir `"$BarnDir`""
|
||||||
|
|
||||||
|
Write-Info "Creating service..."
|
||||||
|
$result = sc.exe create $ServiceName binPath= $binPath DisplayName= $ServiceDisplayName start= auto
|
||||||
|
if ($LASTEXITCODE -ne 0) {
|
||||||
|
Write-Err "Failed to create service: $result"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Set description
|
||||||
|
sc.exe description $ServiceName "Cross-platform job daemon for media processing" | Out-Null
|
||||||
|
|
||||||
|
# Configure failure recovery (restart after 5 seconds)
|
||||||
|
sc.exe failure $ServiceName reset= 86400 actions= restart/5000/restart/5000/restart/5000 | Out-Null
|
||||||
|
|
||||||
|
Write-Info "Service created: $ServiceName"
|
||||||
|
|
||||||
|
# Start the service
|
||||||
|
Write-Info "Starting service..."
|
||||||
|
Start-Service -Name $ServiceName
|
||||||
|
|
||||||
|
# Verify it's running
|
||||||
|
Start-Sleep -Seconds 2
|
||||||
|
$service = Get-Service -Name $ServiceName
|
||||||
|
if ($service.Status -eq "Running") {
|
||||||
|
Write-Info "Service is running"
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Write-Warn "Service may not have started correctly. Status: $($service.Status)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function Install-ScheduledTask {
|
||||||
|
param([string]$BinaryPath)
|
||||||
|
|
||||||
|
Write-Info "Setting up Scheduled Task (user mode)..."
|
||||||
|
|
||||||
|
# Create barn data directory
|
||||||
|
if (-not (Test-Path $BarnDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $BarnDir -Force | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
$taskName = "BarnJobDaemon"
|
||||||
|
|
||||||
|
# Remove existing task if present
|
||||||
|
$existingTask = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
|
||||||
|
if ($existingTask) {
|
||||||
|
Write-Info "Removing existing scheduled task..."
|
||||||
|
Unregister-ScheduledTask -TaskName $taskName -Confirm:$false
|
||||||
|
}
|
||||||
|
|
||||||
|
# Create action
|
||||||
|
$action = New-ScheduledTaskAction -Execute $BinaryPath -Argument "service start --foreground --barn-dir `"$BarnDir`""
|
||||||
|
|
||||||
|
# Create trigger (at logon)
|
||||||
|
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
|
||||||
|
|
||||||
|
# Create settings
|
||||||
|
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1)
|
||||||
|
|
||||||
|
# Register task
|
||||||
|
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Description "Barn Job Daemon" | Out-Null
|
||||||
|
|
||||||
|
Write-Info "Scheduled task created: $taskName"
|
||||||
|
|
||||||
|
# Start the task now
|
||||||
|
Write-Info "Starting barn..."
|
||||||
|
Start-ScheduledTask -TaskName $taskName
|
||||||
|
|
||||||
|
Start-Sleep -Seconds 2
|
||||||
|
Write-Info "Barn is running"
|
||||||
|
}
|
||||||
|
|
||||||
|
function Main {
|
||||||
|
Write-Host "========================================"
|
||||||
|
Write-Host " Barn Installer for Windows"
|
||||||
|
Write-Host "========================================"
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
$isAdmin = Test-Administrator
|
||||||
|
|
||||||
|
if (-not $isAdmin) {
|
||||||
|
Write-Warn "Not running as Administrator."
|
||||||
|
Write-Warn "Will install for current user only (using Scheduled Task instead of Windows Service)."
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
# Adjust install directory for non-admin
|
||||||
|
$InstallDir = Join-Path $env:LOCALAPPDATA "barn"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Info "Install directory: $InstallDir"
|
||||||
|
Write-Info "Data directory: $BarnDir"
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
$version = Get-LatestVersion
|
||||||
|
$binaryPath = Install-Binary -Version $version
|
||||||
|
|
||||||
|
if ($isAdmin) {
|
||||||
|
Add-ToPath -Directory $InstallDir
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
# Add to user PATH
|
||||||
|
$currentPath = [Environment]::GetEnvironmentVariable("Path", "User")
|
||||||
|
if ($currentPath -notlike "*$InstallDir*") {
|
||||||
|
Write-Info "Adding $InstallDir to user PATH..."
|
||||||
|
$newPath = "$currentPath;$InstallDir"
|
||||||
|
[Environment]::SetEnvironmentVariable("Path", $newPath, "User")
|
||||||
|
$env:Path = "$env:Path;$InstallDir"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (-not $NoService) {
|
||||||
|
if ($isAdmin) {
|
||||||
|
Install-WindowsService -BinaryPath $binaryPath
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Install-ScheduledTask -BinaryPath $binaryPath
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
Write-Info "Skipping service setup (use -NoService to disable)"
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "========================================"
|
||||||
|
Write-Info "Barn installation complete!"
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Commands:"
|
||||||
|
Write-Host " barn status - Show job status"
|
||||||
|
Write-Host " barn run -- <cmd> - Run a command as a job"
|
||||||
|
Write-Host " barn service status - Show service status"
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "Data directory: $BarnDir"
|
||||||
|
Write-Host "========================================"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Run main
|
||||||
|
Main
|
||||||
Executable
+307
@@ -0,0 +1,307 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
# Barn Installer Script
|
||||||
|
# Usage: curl -fsSL https://raw.githubusercontent.com/samson-media/barn/main/install.sh | sh
|
||||||
|
#
|
||||||
|
# This script installs the Barn job daemon and sets it up to run on startup.
|
||||||
|
# Supports: Linux (systemd), macOS (launchd)
|
||||||
|
|
||||||
|
set -e
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
REPO="samson-media/barn"
|
||||||
|
INSTALL_DIR="/usr/local/bin"
|
||||||
|
BARN_DIR="" # Will be set based on OS
|
||||||
|
|
||||||
|
# Colors for output
|
||||||
|
RED='\033[0;31m'
|
||||||
|
GREEN='\033[0;32m'
|
||||||
|
YELLOW='\033[1;33m'
|
||||||
|
NC='\033[0m' # No Color
|
||||||
|
|
||||||
|
# Print functions
|
||||||
|
info() {
|
||||||
|
printf "${GREEN}[INFO]${NC} %s\n" "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
warn() {
|
||||||
|
printf "${YELLOW}[WARN]${NC} %s\n" "$1"
|
||||||
|
}
|
||||||
|
|
||||||
|
error() {
|
||||||
|
printf "${RED}[ERROR]${NC} %s\n" "$1"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Detect OS
|
||||||
|
detect_os() {
|
||||||
|
case "$(uname -s)" in
|
||||||
|
Linux*) OS="linux" ;;
|
||||||
|
Darwin*) OS="macos" ;;
|
||||||
|
*) error "Unsupported operating system: $(uname -s)" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
# Detect architecture
|
||||||
|
detect_arch() {
|
||||||
|
case "$(uname -m)" in
|
||||||
|
x86_64|amd64) ARCH="x64" ;;
|
||||||
|
aarch64|arm64) ARCH="arm64" ;;
|
||||||
|
*) error "Unsupported architecture: $(uname -m)" ;;
|
||||||
|
esac
|
||||||
|
}
|
||||||
|
|
||||||
|
# Get latest release version
|
||||||
|
get_latest_version() {
|
||||||
|
VERSION=$(curl -fsSL "https://api.github.com/repos/${REPO}/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/')
|
||||||
|
if [ -z "$VERSION" ]; then
|
||||||
|
error "Failed to get latest version"
|
||||||
|
fi
|
||||||
|
info "Latest version: $VERSION"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Download and install binary
|
||||||
|
install_binary() {
|
||||||
|
BINARY_NAME="barn-${OS}-${ARCH}"
|
||||||
|
DOWNLOAD_URL="https://github.com/${REPO}/releases/download/${VERSION}/${BINARY_NAME}"
|
||||||
|
|
||||||
|
info "Downloading $BINARY_NAME..."
|
||||||
|
|
||||||
|
# Create temp directory
|
||||||
|
TMP_DIR=$(mktemp -d)
|
||||||
|
trap "rm -rf $TMP_DIR" EXIT
|
||||||
|
|
||||||
|
# Download binary
|
||||||
|
if ! curl -fsSL "$DOWNLOAD_URL" -o "$TMP_DIR/barn"; then
|
||||||
|
error "Failed to download binary from $DOWNLOAD_URL"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Make executable
|
||||||
|
chmod +x "$TMP_DIR/barn"
|
||||||
|
|
||||||
|
# Verify it works
|
||||||
|
if ! "$TMP_DIR/barn" --version > /dev/null 2>&1; then
|
||||||
|
error "Downloaded binary is not executable or corrupted"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Install to destination
|
||||||
|
if [ -w "$INSTALL_DIR" ]; then
|
||||||
|
mv "$TMP_DIR/barn" "$INSTALL_DIR/barn"
|
||||||
|
else
|
||||||
|
info "Installing to $INSTALL_DIR requires sudo..."
|
||||||
|
sudo mv "$TMP_DIR/barn" "$INSTALL_DIR/barn"
|
||||||
|
fi
|
||||||
|
|
||||||
|
info "Installed barn to $INSTALL_DIR/barn"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Setup systemd service (Linux)
|
||||||
|
setup_systemd() {
|
||||||
|
info "Setting up systemd service..."
|
||||||
|
|
||||||
|
# Determine if we should use user or system service
|
||||||
|
if [ "$(id -u)" -eq 0 ]; then
|
||||||
|
# Running as root - install system service
|
||||||
|
SERVICE_FILE="/etc/systemd/system/barn.service"
|
||||||
|
BARN_DIR="/var/lib/barn"
|
||||||
|
USER_MODE=""
|
||||||
|
SYSTEMCTL_CMD="systemctl"
|
||||||
|
else
|
||||||
|
# Running as user - install user service
|
||||||
|
SERVICE_FILE="$HOME/.config/systemd/user/barn.service"
|
||||||
|
BARN_DIR="$HOME/.local/share/barn"
|
||||||
|
USER_MODE="--user"
|
||||||
|
SYSTEMCTL_CMD="systemctl --user"
|
||||||
|
|
||||||
|
# Create directory if needed
|
||||||
|
mkdir -p "$(dirname "$SERVICE_FILE")"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Create barn data directory
|
||||||
|
mkdir -p "$BARN_DIR"
|
||||||
|
|
||||||
|
# Generate service file
|
||||||
|
if [ -n "$USER_MODE" ]; then
|
||||||
|
# User service
|
||||||
|
cat > "$SERVICE_FILE" << EOF
|
||||||
|
[Unit]
|
||||||
|
Description=Barn Job Daemon (User)
|
||||||
|
Documentation=https://github.com/samson-media/barn
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=$INSTALL_DIR/barn service start --foreground --barn-dir $BARN_DIR
|
||||||
|
ExecStop=$INSTALL_DIR/barn service stop --barn-dir $BARN_DIR
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=default.target
|
||||||
|
EOF
|
||||||
|
else
|
||||||
|
# System service
|
||||||
|
sudo tee "$SERVICE_FILE" > /dev/null << EOF
|
||||||
|
[Unit]
|
||||||
|
Description=Barn Job Daemon
|
||||||
|
Documentation=https://github.com/samson-media/barn
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
ExecStart=$INSTALL_DIR/barn service start --foreground --barn-dir $BARN_DIR
|
||||||
|
ExecStop=$INSTALL_DIR/barn service stop --barn-dir $BARN_DIR
|
||||||
|
ExecReload=/bin/kill -HUP \$MAINPID
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=5
|
||||||
|
|
||||||
|
# Security hardening
|
||||||
|
NoNewPrivileges=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=read-only
|
||||||
|
PrivateTmp=false
|
||||||
|
ReadWritePaths=$BARN_DIR
|
||||||
|
|
||||||
|
# Logging
|
||||||
|
StandardOutput=journal
|
||||||
|
StandardError=journal
|
||||||
|
SyslogIdentifier=barn
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
info "Created service file: $SERVICE_FILE"
|
||||||
|
|
||||||
|
# Reload systemd
|
||||||
|
$SYSTEMCTL_CMD daemon-reload
|
||||||
|
|
||||||
|
# Enable service
|
||||||
|
$SYSTEMCTL_CMD enable barn
|
||||||
|
info "Enabled barn service to start on boot"
|
||||||
|
|
||||||
|
# Start service
|
||||||
|
$SYSTEMCTL_CMD start barn
|
||||||
|
info "Started barn service"
|
||||||
|
|
||||||
|
# Show status
|
||||||
|
$SYSTEMCTL_CMD status barn --no-pager || true
|
||||||
|
}
|
||||||
|
|
||||||
|
# Setup launchd service (macOS)
|
||||||
|
setup_launchd() {
|
||||||
|
info "Setting up launchd service..."
|
||||||
|
|
||||||
|
# Always install as user agent on macOS
|
||||||
|
PLIST_FILE="$HOME/Library/LaunchAgents/com.samsonmedia.barn.plist"
|
||||||
|
BARN_DIR="$HOME/Library/Application Support/barn"
|
||||||
|
LOGS_DIR="$BARN_DIR/logs"
|
||||||
|
|
||||||
|
# Create directories
|
||||||
|
mkdir -p "$(dirname "$PLIST_FILE")"
|
||||||
|
mkdir -p "$BARN_DIR"
|
||||||
|
mkdir -p "$LOGS_DIR"
|
||||||
|
|
||||||
|
# Generate plist file
|
||||||
|
cat > "$PLIST_FILE" << EOF
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
|
||||||
|
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||||
|
<plist version="1.0">
|
||||||
|
<dict>
|
||||||
|
<key>Label</key>
|
||||||
|
<string>com.samsonmedia.barn</string>
|
||||||
|
|
||||||
|
<key>ProgramArguments</key>
|
||||||
|
<array>
|
||||||
|
<string>$INSTALL_DIR/barn</string>
|
||||||
|
<string>service</string>
|
||||||
|
<string>start</string>
|
||||||
|
<string>--foreground</string>
|
||||||
|
<string>--barn-dir</string>
|
||||||
|
<string>$BARN_DIR</string>
|
||||||
|
</array>
|
||||||
|
|
||||||
|
<key>RunAtLoad</key>
|
||||||
|
<true/>
|
||||||
|
|
||||||
|
<key>KeepAlive</key>
|
||||||
|
<true/>
|
||||||
|
|
||||||
|
<key>StandardOutPath</key>
|
||||||
|
<string>$LOGS_DIR/barn.log</string>
|
||||||
|
|
||||||
|
<key>StandardErrorPath</key>
|
||||||
|
<string>$LOGS_DIR/barn.log</string>
|
||||||
|
|
||||||
|
<key>WorkingDirectory</key>
|
||||||
|
<string>$BARN_DIR</string>
|
||||||
|
</dict>
|
||||||
|
</plist>
|
||||||
|
EOF
|
||||||
|
|
||||||
|
info "Created plist file: $PLIST_FILE"
|
||||||
|
|
||||||
|
# Unload if already loaded (ignore errors)
|
||||||
|
launchctl unload "$PLIST_FILE" 2>/dev/null || true
|
||||||
|
|
||||||
|
# Load the service
|
||||||
|
launchctl load "$PLIST_FILE"
|
||||||
|
info "Loaded barn service into launchd"
|
||||||
|
|
||||||
|
# Start the service
|
||||||
|
launchctl start com.samsonmedia.barn
|
||||||
|
info "Started barn service"
|
||||||
|
|
||||||
|
# Verify it's running
|
||||||
|
sleep 2
|
||||||
|
if launchctl list | grep -q "com.samsonmedia.barn"; then
|
||||||
|
info "Barn service is running"
|
||||||
|
else
|
||||||
|
warn "Barn service may not have started correctly. Check logs at $LOGS_DIR/barn.log"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
# Main installation function
|
||||||
|
main() {
|
||||||
|
echo "========================================"
|
||||||
|
echo " Barn Installer"
|
||||||
|
echo "========================================"
|
||||||
|
echo ""
|
||||||
|
|
||||||
|
detect_os
|
||||||
|
detect_arch
|
||||||
|
info "Detected: $OS-$ARCH"
|
||||||
|
|
||||||
|
get_latest_version
|
||||||
|
install_binary
|
||||||
|
|
||||||
|
# Setup service based on OS
|
||||||
|
case "$OS" in
|
||||||
|
linux)
|
||||||
|
if [ -d "/run/systemd/system" ]; then
|
||||||
|
setup_systemd
|
||||||
|
else
|
||||||
|
warn "systemd not detected. Barn installed but not configured to run on startup."
|
||||||
|
warn "You can manually run: barn service start"
|
||||||
|
fi
|
||||||
|
;;
|
||||||
|
macos)
|
||||||
|
setup_launchd
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "========================================"
|
||||||
|
info "Barn installation complete!"
|
||||||
|
echo ""
|
||||||
|
echo "Commands:"
|
||||||
|
echo " barn status - Show job status"
|
||||||
|
echo " barn run -- <cmd> - Run a command as a job"
|
||||||
|
echo " barn service status - Show service status"
|
||||||
|
echo ""
|
||||||
|
echo "Data directory: $BARN_DIR"
|
||||||
|
echo "========================================"
|
||||||
|
}
|
||||||
|
|
||||||
|
# Run main
|
||||||
|
main
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
; Barn Installer Script for Inno Setup
|
||||||
|
; This script generates a Windows setup.exe installer
|
||||||
|
; Build: iscc barn.iss (requires Inno Setup 6+)
|
||||||
|
|
||||||
|
#define AppName "Barn"
|
||||||
|
#define AppPublisher "Samson Media"
|
||||||
|
#define AppURL "https://github.com/samson-media/barn"
|
||||||
|
#define AppExeName "barn.exe"
|
||||||
|
|
||||||
|
; Version is passed from CI: iscc /DAppVersion=0.1.0 barn.iss
|
||||||
|
#ifndef AppVersion
|
||||||
|
#define AppVersion "0.0.0"
|
||||||
|
#endif
|
||||||
|
|
||||||
|
[Setup]
|
||||||
|
AppId={{7B8A9C5E-4D3F-2A1B-0E9D-8C7B6A5F4E3D}
|
||||||
|
AppName={#AppName}
|
||||||
|
AppVersion={#AppVersion}
|
||||||
|
AppVerName={#AppName} {#AppVersion}
|
||||||
|
AppPublisher={#AppPublisher}
|
||||||
|
AppPublisherURL={#AppURL}
|
||||||
|
AppSupportURL={#AppURL}/issues
|
||||||
|
DefaultDirName={autopf}\{#AppName}
|
||||||
|
DefaultGroupName={#AppName}
|
||||||
|
AllowNoIcons=yes
|
||||||
|
LicenseFile=..\LICENSE
|
||||||
|
OutputDir=..\dist
|
||||||
|
OutputBaseFilename=setup-barn-v{#AppVersion}-windows-x64
|
||||||
|
Compression=lzma2
|
||||||
|
SolidCompression=yes
|
||||||
|
WizardStyle=modern
|
||||||
|
PrivilegesRequired=admin
|
||||||
|
ArchitecturesAllowed=x64compatible
|
||||||
|
ArchitecturesInstallIn64BitMode=x64compatible
|
||||||
|
ChangesEnvironment=yes
|
||||||
|
|
||||||
|
[Languages]
|
||||||
|
Name: "english"; MessagesFile: "compiler:Default.isl"
|
||||||
|
|
||||||
|
[Tasks]
|
||||||
|
Name: "addtopath"; Description: "Add to PATH environment variable"; GroupDescription: "Additional options:"
|
||||||
|
Name: "installservice"; Description: "Install and start Windows Service"; GroupDescription: "Service options:"; Flags: checkedonce
|
||||||
|
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
|
||||||
|
|
||||||
|
[Files]
|
||||||
|
Source: "..\target\barn-windows-x64.exe"; DestDir: "{app}"; DestName: "{#AppExeName}"; Flags: ignoreversion
|
||||||
|
|
||||||
|
[Icons]
|
||||||
|
Name: "{group}\{#AppName} Status"; Filename: "{app}\{#AppExeName}"; Parameters: "status"
|
||||||
|
Name: "{group}\{#AppName} Service Status"; Filename: "{app}\{#AppExeName}"; Parameters: "service status"
|
||||||
|
Name: "{group}\Uninstall {#AppName}"; Filename: "{uninstallexe}"
|
||||||
|
Name: "{autodesktop}\{#AppName}"; Filename: "{app}\{#AppExeName}"; Tasks: desktopicon
|
||||||
|
|
||||||
|
[Registry]
|
||||||
|
Root: HKLM; Subkey: "SYSTEM\CurrentControlSet\Control\Session Manager\Environment"; \
|
||||||
|
ValueType: expandsz; ValueName: "Path"; ValueData: "{olddata};{app}"; \
|
||||||
|
Tasks: addtopath; Check: NeedsAddPath('{app}')
|
||||||
|
|
||||||
|
[Run]
|
||||||
|
Filename: "{app}\{#AppExeName}"; Parameters: "service install"; \
|
||||||
|
StatusMsg: "Installing Windows Service..."; Tasks: installservice; Flags: runhidden
|
||||||
|
Filename: "{app}\{#AppExeName}"; Parameters: "service start"; \
|
||||||
|
StatusMsg: "Starting Barn service..."; Tasks: installservice; Flags: runhidden
|
||||||
|
|
||||||
|
[UninstallRun]
|
||||||
|
Filename: "{app}\{#AppExeName}"; Parameters: "service stop"; Flags: runhidden; RunOnceId: "StopService"
|
||||||
|
Filename: "{app}\{#AppExeName}"; Parameters: "service uninstall"; Flags: runhidden; RunOnceId: "UninstallService"
|
||||||
|
|
||||||
|
[Code]
|
||||||
|
function NeedsAddPath(Param: string): boolean;
|
||||||
|
var
|
||||||
|
OrigPath: string;
|
||||||
|
begin
|
||||||
|
if not RegQueryStringValue(HKEY_LOCAL_MACHINE,
|
||||||
|
'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
|
||||||
|
'Path', OrigPath)
|
||||||
|
then begin
|
||||||
|
Result := True;
|
||||||
|
exit;
|
||||||
|
end;
|
||||||
|
Result := Pos(';' + Param + ';', ';' + OrigPath + ';') = 0;
|
||||||
|
end;
|
||||||
|
|
||||||
|
procedure CurUninstallStepChanged(CurUninstallStep: TUninstallStep);
|
||||||
|
var
|
||||||
|
Path: string;
|
||||||
|
AppPath: string;
|
||||||
|
P: Integer;
|
||||||
|
begin
|
||||||
|
if CurUninstallStep = usPostUninstall then
|
||||||
|
begin
|
||||||
|
if RegQueryStringValue(HKEY_LOCAL_MACHINE,
|
||||||
|
'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
|
||||||
|
'Path', Path) then
|
||||||
|
begin
|
||||||
|
AppPath := ExpandConstant('{app}');
|
||||||
|
P := Pos(';' + AppPath, Path);
|
||||||
|
if P > 0 then
|
||||||
|
begin
|
||||||
|
Delete(Path, P, Length(';' + AppPath));
|
||||||
|
RegWriteStringValue(HKEY_LOCAL_MACHINE,
|
||||||
|
'SYSTEM\CurrentControlSet\Control\Session Manager\Environment',
|
||||||
|
'Path', Path);
|
||||||
|
end;
|
||||||
|
end;
|
||||||
|
end;
|
||||||
|
end;
|
||||||
@@ -237,7 +237,7 @@ public class HumanFormatter implements OutputFormatter {
|
|||||||
case QUEUED -> colorize(text, CYAN);
|
case QUEUED -> colorize(text, CYAN);
|
||||||
case RUNNING -> colorize(text, YELLOW);
|
case RUNNING -> colorize(text, YELLOW);
|
||||||
case SUCCEEDED -> colorize(text, GREEN);
|
case SUCCEEDED -> colorize(text, GREEN);
|
||||||
case FAILED -> colorize(text, RED);
|
case FAILED, KILLED -> colorize(text, RED);
|
||||||
case CANCELED -> text;
|
case CANCELED -> text;
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,16 +113,7 @@ public class ServiceRestartCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private int startService(Path effectiveBarnDir) throws IOException {
|
private int startService(Path effectiveBarnDir) throws IOException {
|
||||||
String javaHome = System.getProperty("java.home");
|
ProcessBuilder pb = buildDaemonCommand(effectiveBarnDir);
|
||||||
String classPath = System.getProperty("java.class.path");
|
|
||||||
|
|
||||||
ProcessBuilder pb = new ProcessBuilder(
|
|
||||||
Path.of(javaHome, "bin", "java").toString(),
|
|
||||||
"-cp", classPath,
|
|
||||||
"com.samsonmedia.barn.Main",
|
|
||||||
"service", "start", "--foreground",
|
|
||||||
"--barn-dir", effectiveBarnDir.toString()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (globalOptions != null && globalOptions.getConfigPath().isPresent()) {
|
if (globalOptions != null && globalOptions.getConfigPath().isPresent()) {
|
||||||
pb.command().add("--config");
|
pb.command().add("--config");
|
||||||
@@ -162,4 +153,33 @@ public class ServiceRestartCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
return ConfigDefaults.getDefaultBaseDir();
|
return ConfigDefaults.getDefaultBaseDir();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ProcessBuilder buildDaemonCommand(Path effectiveBarnDir) {
|
||||||
|
// Check if running as a native image
|
||||||
|
if (isNativeImage()) {
|
||||||
|
// In native image, re-exec the current executable
|
||||||
|
String executable = ProcessHandle.current().info().command().orElse("barn");
|
||||||
|
return new ProcessBuilder(
|
||||||
|
executable,
|
||||||
|
"service", "start", "--foreground",
|
||||||
|
"--barn-dir", effectiveBarnDir.toString()
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Running in JVM, use java command
|
||||||
|
String javaHome = System.getProperty("java.home");
|
||||||
|
String classPath = System.getProperty("java.class.path");
|
||||||
|
return new ProcessBuilder(
|
||||||
|
Path.of(javaHome, "bin", "java").toString(),
|
||||||
|
"-cp", classPath,
|
||||||
|
"com.samsonmedia.barn.Main",
|
||||||
|
"service", "start", "--foreground",
|
||||||
|
"--barn-dir", effectiveBarnDir.toString()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isNativeImage() {
|
||||||
|
// GraalVM sets this property when running as native image
|
||||||
|
return System.getProperty("org.graalvm.nativeimage.imagecode") != null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -99,18 +99,9 @@ public class ServiceStartCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private int startDaemon(Path effectiveBarnDir) throws IOException {
|
private int startDaemon(Path effectiveBarnDir) throws IOException {
|
||||||
// For daemonizing, we re-exec with --foreground and nohup
|
// For daemonizing, we re-exec with --foreground
|
||||||
// This is a simplified approach; production would use proper daemon techniques
|
// This is a simplified approach; production would use proper daemon techniques
|
||||||
String javaHome = System.getProperty("java.home");
|
ProcessBuilder pb = buildDaemonCommand(effectiveBarnDir);
|
||||||
String classPath = System.getProperty("java.class.path");
|
|
||||||
|
|
||||||
ProcessBuilder pb = new ProcessBuilder(
|
|
||||||
Path.of(javaHome, "bin", "java").toString(),
|
|
||||||
"-cp", classPath,
|
|
||||||
"com.samsonmedia.barn.Main",
|
|
||||||
"service", "start", "--foreground",
|
|
||||||
"--barn-dir", effectiveBarnDir.toString()
|
|
||||||
);
|
|
||||||
|
|
||||||
if (globalOptions != null && globalOptions.getConfigPath().isPresent()) {
|
if (globalOptions != null && globalOptions.getConfigPath().isPresent()) {
|
||||||
pb.command().add("--config");
|
pb.command().add("--config");
|
||||||
@@ -186,4 +177,33 @@ public class ServiceStartCommand extends BaseCommand {
|
|||||||
}
|
}
|
||||||
return ConfigDefaults.getDefaultBaseDir();
|
return ConfigDefaults.getDefaultBaseDir();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private ProcessBuilder buildDaemonCommand(Path effectiveBarnDir) {
|
||||||
|
// Check if running as a native image
|
||||||
|
if (isNativeImage()) {
|
||||||
|
// In native image, re-exec the current executable
|
||||||
|
String executable = ProcessHandle.current().info().command().orElse("barn");
|
||||||
|
return new ProcessBuilder(
|
||||||
|
executable,
|
||||||
|
"service", "start", "--foreground",
|
||||||
|
"--barn-dir", effectiveBarnDir.toString()
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
// Running in JVM, use java command
|
||||||
|
String javaHome = System.getProperty("java.home");
|
||||||
|
String classPath = System.getProperty("java.class.path");
|
||||||
|
return new ProcessBuilder(
|
||||||
|
Path.of(javaHome, "bin", "java").toString(),
|
||||||
|
"-cp", classPath,
|
||||||
|
"com.samsonmedia.barn.Main",
|
||||||
|
"service", "start", "--foreground",
|
||||||
|
"--barn-dir", effectiveBarnDir.toString()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private boolean isNativeImage() {
|
||||||
|
// GraalVM sets this property when running as native image
|
||||||
|
return System.getProperty("org.graalvm.nativeimage.imagecode") != null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -98,10 +98,11 @@ public class ServiceStatusCommand extends BaseCommand {
|
|||||||
int succeeded = countJobsByState(effectiveBarnDir, JobState.SUCCEEDED);
|
int succeeded = countJobsByState(effectiveBarnDir, JobState.SUCCEEDED);
|
||||||
int failed = countJobsByState(effectiveBarnDir, JobState.FAILED);
|
int failed = countJobsByState(effectiveBarnDir, JobState.FAILED);
|
||||||
int canceled = countJobsByState(effectiveBarnDir, JobState.CANCELED);
|
int canceled = countJobsByState(effectiveBarnDir, JobState.CANCELED);
|
||||||
|
int killed = countJobsByState(effectiveBarnDir, JobState.KILLED);
|
||||||
int total = countTotalJobs(effectiveBarnDir);
|
int total = countTotalJobs(effectiveBarnDir);
|
||||||
|
|
||||||
return ServiceStatus.running(pid, startTime, running, queued, succeeded, failed,
|
return ServiceStatus.running(pid, startTime, running, queued, succeeded, failed,
|
||||||
canceled, total, effectiveBarnDir, serviceManager);
|
canceled, killed, total, effectiveBarnDir, serviceManager);
|
||||||
}
|
}
|
||||||
} catch (IpcException e) {
|
} catch (IpcException e) {
|
||||||
LOG.debug("IPC failed, using basic status: {}", e.getMessage());
|
LOG.debug("IPC failed, using basic status: {}", e.getMessage());
|
||||||
@@ -115,9 +116,10 @@ public class ServiceStatusCommand extends BaseCommand {
|
|||||||
int succeeded = countJobsByState(effectiveBarnDir, JobState.SUCCEEDED);
|
int succeeded = countJobsByState(effectiveBarnDir, JobState.SUCCEEDED);
|
||||||
int failed = countJobsByState(effectiveBarnDir, JobState.FAILED);
|
int failed = countJobsByState(effectiveBarnDir, JobState.FAILED);
|
||||||
int canceled = countJobsByState(effectiveBarnDir, JobState.CANCELED);
|
int canceled = countJobsByState(effectiveBarnDir, JobState.CANCELED);
|
||||||
|
int killed = countJobsByState(effectiveBarnDir, JobState.KILLED);
|
||||||
|
|
||||||
return ServiceStatus.running(pid, startTime, running, queued, succeeded, failed, canceled,
|
return ServiceStatus.running(pid, startTime, running, queued, succeeded, failed, canceled,
|
||||||
total, effectiveBarnDir, serviceManager);
|
killed, total, effectiveBarnDir, serviceManager);
|
||||||
}
|
}
|
||||||
|
|
||||||
private int getIntValue(Map<String, Object> map, String key, int defaultValue) {
|
private int getIntValue(Map<String, Object> map, String key, int defaultValue) {
|
||||||
@@ -182,6 +184,7 @@ public class ServiceStatusCommand extends BaseCommand {
|
|||||||
sb.append(String.format(" Succeeded: %d%n", status.succeededJobs));
|
sb.append(String.format(" Succeeded: %d%n", status.succeededJobs));
|
||||||
sb.append(String.format(" Failed: %d%n", status.failedJobs));
|
sb.append(String.format(" Failed: %d%n", status.failedJobs));
|
||||||
sb.append(String.format(" Canceled: %d%n", status.canceledJobs));
|
sb.append(String.format(" Canceled: %d%n", status.canceledJobs));
|
||||||
|
sb.append(String.format(" Killed: %d%n", status.killedJobs));
|
||||||
sb.append(String.format(" Total: %d%n", status.totalJobs));
|
sb.append(String.format(" Total: %d%n", status.totalJobs));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,13 +257,14 @@ public class ServiceStatusCommand extends BaseCommand {
|
|||||||
final int succeededJobs;
|
final int succeededJobs;
|
||||||
final int failedJobs;
|
final int failedJobs;
|
||||||
final int canceledJobs;
|
final int canceledJobs;
|
||||||
|
final int killedJobs;
|
||||||
final int totalJobs;
|
final int totalJobs;
|
||||||
final Path dataDir;
|
final Path dataDir;
|
||||||
final String serviceManager;
|
final String serviceManager;
|
||||||
|
|
||||||
private ServiceStatus(boolean running, long pid, Instant startedAt, long uptimeSeconds,
|
private ServiceStatus(boolean running, long pid, Instant startedAt, long uptimeSeconds,
|
||||||
int runningJobs, int queuedJobs, int succeededJobs, int failedJobs, int canceledJobs,
|
int runningJobs, int queuedJobs, int succeededJobs, int failedJobs, int canceledJobs,
|
||||||
int totalJobs, Path dataDir, String serviceManager) {
|
int killedJobs, int totalJobs, Path dataDir, String serviceManager) {
|
||||||
this.running = running;
|
this.running = running;
|
||||||
this.pid = pid;
|
this.pid = pid;
|
||||||
this.startedAt = startedAt;
|
this.startedAt = startedAt;
|
||||||
@@ -270,21 +274,22 @@ public class ServiceStatusCommand extends BaseCommand {
|
|||||||
this.succeededJobs = succeededJobs;
|
this.succeededJobs = succeededJobs;
|
||||||
this.failedJobs = failedJobs;
|
this.failedJobs = failedJobs;
|
||||||
this.canceledJobs = canceledJobs;
|
this.canceledJobs = canceledJobs;
|
||||||
|
this.killedJobs = killedJobs;
|
||||||
this.totalJobs = totalJobs;
|
this.totalJobs = totalJobs;
|
||||||
this.dataDir = dataDir;
|
this.dataDir = dataDir;
|
||||||
this.serviceManager = serviceManager;
|
this.serviceManager = serviceManager;
|
||||||
}
|
}
|
||||||
|
|
||||||
static ServiceStatus stopped(Path dataDir, String serviceManager) {
|
static ServiceStatus stopped(Path dataDir, String serviceManager) {
|
||||||
return new ServiceStatus(false, 0, null, 0, 0, 0, 0, 0, 0, 0, dataDir, serviceManager);
|
return new ServiceStatus(false, 0, null, 0, 0, 0, 0, 0, 0, 0, 0, dataDir, serviceManager);
|
||||||
}
|
}
|
||||||
|
|
||||||
static ServiceStatus running(long pid, Instant startedAt, int runningJobs, int queuedJobs,
|
static ServiceStatus running(long pid, Instant startedAt, int runningJobs, int queuedJobs,
|
||||||
int succeededJobs, int failedJobs, int canceledJobs, int totalJobs,
|
int succeededJobs, int failedJobs, int canceledJobs, int killedJobs, int totalJobs,
|
||||||
Path dataDir, String serviceManager) {
|
Path dataDir, String serviceManager) {
|
||||||
long uptime = Duration.between(startedAt, Instant.now()).getSeconds();
|
long uptime = Duration.between(startedAt, Instant.now()).getSeconds();
|
||||||
return new ServiceStatus(true, pid, startedAt, uptime, runningJobs, queuedJobs,
|
return new ServiceStatus(true, pid, startedAt, uptime, runningJobs, queuedJobs,
|
||||||
succeededJobs, failedJobs, canceledJobs, totalJobs, dataDir, serviceManager);
|
succeededJobs, failedJobs, canceledJobs, killedJobs, totalJobs, dataDir, serviceManager);
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, Object> toMap() {
|
Map<String, Object> toMap() {
|
||||||
@@ -303,6 +308,7 @@ public class ServiceStatusCommand extends BaseCommand {
|
|||||||
jobs.put("succeeded", succeededJobs);
|
jobs.put("succeeded", succeededJobs);
|
||||||
jobs.put("failed", failedJobs);
|
jobs.put("failed", failedJobs);
|
||||||
jobs.put("canceled", canceledJobs);
|
jobs.put("canceled", canceledJobs);
|
||||||
|
jobs.put("killed", killedJobs);
|
||||||
jobs.put("total", totalJobs);
|
jobs.put("total", totalJobs);
|
||||||
map.put("jobs", jobs);
|
map.put("jobs", jobs);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,11 +28,13 @@ public final class ConfigDefaults {
|
|||||||
/**
|
/**
|
||||||
* Gets the default IPC socket path.
|
* Gets the default IPC socket path.
|
||||||
*
|
*
|
||||||
|
* <p>Windows 10 version 1803+ supports Unix domain sockets with file paths.
|
||||||
|
*
|
||||||
* @return the default IPC socket path
|
* @return the default IPC socket path
|
||||||
*/
|
*/
|
||||||
public static Path getDefaultIpcSocket() {
|
public static Path getDefaultIpcSocket() {
|
||||||
return switch (OperatingSystem.current()) {
|
return switch (OperatingSystem.current()) {
|
||||||
case WINDOWS -> Path.of("\\\\.\\pipe\\barn");
|
case WINDOWS -> Path.of(System.getenv("TEMP"), "barn", "barn.sock");
|
||||||
case LINUX, MACOS -> Path.of("/tmp/barn/barn.sock");
|
case LINUX, MACOS -> Path.of("/tmp/barn/barn.sock");
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package com.samsonmedia.barn.execution;
|
package com.samsonmedia.barn.execution;
|
||||||
|
|
||||||
import java.io.IOException;
|
import java.io.IOException;
|
||||||
|
import java.time.Instant;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Objects;
|
import java.util.Objects;
|
||||||
@@ -8,8 +9,10 @@ import java.util.Objects;
|
|||||||
import org.slf4j.Logger;
|
import org.slf4j.Logger;
|
||||||
import org.slf4j.LoggerFactory;
|
import org.slf4j.LoggerFactory;
|
||||||
|
|
||||||
|
import com.samsonmedia.barn.config.Config;
|
||||||
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.RetryCalculator;
|
||||||
import com.samsonmedia.barn.state.BarnDirectories;
|
import com.samsonmedia.barn.state.BarnDirectories;
|
||||||
import com.samsonmedia.barn.state.JobState;
|
import com.samsonmedia.barn.state.JobState;
|
||||||
|
|
||||||
@@ -23,17 +26,19 @@ import com.samsonmedia.barn.state.JobState;
|
|||||||
* <li>Its process is no longer alive (or PID is unknown)</li>
|
* <li>Its process is no longer alive (or PID is unknown)</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
*
|
*
|
||||||
* <p>Orphaned jobs are marked as failed with a symbolic exit code.
|
* <p>Orphaned jobs are marked as KILLED and automatically scheduled for retry
|
||||||
|
* if retries are configured and not exhausted.
|
||||||
*/
|
*/
|
||||||
public class CrashRecovery {
|
public class CrashRecovery {
|
||||||
|
|
||||||
private static final Logger LOG = LoggerFactory.getLogger(CrashRecovery.class);
|
private static final Logger LOG = LoggerFactory.getLogger(CrashRecovery.class);
|
||||||
private static final String ORPHANED_EXIT_CODE = "orphaned_process";
|
private static final String KILLED_ERROR = "Process killed - daemon restarted";
|
||||||
private static final String ORPHANED_ERROR = "Process orphaned - daemon restarted";
|
|
||||||
|
|
||||||
private final JobRepository repository;
|
private final JobRepository repository;
|
||||||
private final HeartbeatChecker heartbeatChecker;
|
private final HeartbeatChecker heartbeatChecker;
|
||||||
private final BarnDirectories dirs;
|
private final BarnDirectories dirs;
|
||||||
|
private final RetryCalculator retryCalculator;
|
||||||
|
private final int maxRetries;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates a CrashRecovery instance.
|
* Creates a CrashRecovery instance.
|
||||||
@@ -41,11 +46,16 @@ public class CrashRecovery {
|
|||||||
* @param repository the job repository
|
* @param repository the job repository
|
||||||
* @param heartbeatChecker the heartbeat checker
|
* @param heartbeatChecker the heartbeat checker
|
||||||
* @param dirs the directory manager
|
* @param dirs the directory manager
|
||||||
|
* @param config the configuration
|
||||||
*/
|
*/
|
||||||
public CrashRecovery(JobRepository repository, HeartbeatChecker heartbeatChecker, BarnDirectories dirs) {
|
public CrashRecovery(JobRepository repository, HeartbeatChecker heartbeatChecker, BarnDirectories dirs,
|
||||||
|
Config config) {
|
||||||
this.repository = Objects.requireNonNull(repository, "repository must not be null");
|
this.repository = Objects.requireNonNull(repository, "repository must not be null");
|
||||||
this.heartbeatChecker = Objects.requireNonNull(heartbeatChecker, "heartbeatChecker must not be null");
|
this.heartbeatChecker = Objects.requireNonNull(heartbeatChecker, "heartbeatChecker must not be null");
|
||||||
this.dirs = Objects.requireNonNull(dirs, "dirs must not be null");
|
this.dirs = Objects.requireNonNull(dirs, "dirs must not be null");
|
||||||
|
Objects.requireNonNull(config, "config must not be null");
|
||||||
|
this.retryCalculator = new RetryCalculator(config.jobs());
|
||||||
|
this.maxRetries = config.jobs().maxRetries();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -128,6 +138,18 @@ public class CrashRecovery {
|
|||||||
private void recoverJob(Job job) throws IOException {
|
private void recoverJob(Job job) throws IOException {
|
||||||
LOG.info("Recovering orphaned job: {} (PID: {})", job.id(), job.pid());
|
LOG.info("Recovering orphaned job: {} (PID: {})", job.id(), job.pid());
|
||||||
|
|
||||||
repository.markFailed(job.id(), ORPHANED_EXIT_CODE, ORPHANED_ERROR);
|
// Mark the job as killed
|
||||||
|
repository.markKilled(job.id(), KILLED_ERROR);
|
||||||
|
|
||||||
|
// Check if we should auto-retry
|
||||||
|
if (maxRetries > 0 && job.retryCount() < maxRetries) {
|
||||||
|
// Schedule retry with exponential backoff
|
||||||
|
Instant retryAt = Instant.now().plus(retryCalculator.calculateDelay(job.retryCount()));
|
||||||
|
repository.scheduleRetry(job.id(), retryAt, null, KILLED_ERROR);
|
||||||
|
LOG.info("Job {} scheduled for auto-retry at {} (attempt {})",
|
||||||
|
job.id(), retryAt, job.retryCount() + 1);
|
||||||
|
} else {
|
||||||
|
LOG.info("Job {} will not be retried (retries exhausted or disabled)", job.id());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -257,6 +257,27 @@ public class JobRepository {
|
|||||||
LOG.info("Job {} failed: {}", id, symbolicCode);
|
LOG.info("Job {} failed: {}", id, symbolicCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Marks a job as killed (orphaned when service was terminated).
|
||||||
|
*
|
||||||
|
* @param id the job ID
|
||||||
|
* @param error the error message
|
||||||
|
* @throws IOException if update fails
|
||||||
|
*/
|
||||||
|
public void markKilled(String id, String error) throws IOException {
|
||||||
|
Objects.requireNonNull(id, "id must not be null");
|
||||||
|
|
||||||
|
StateFiles stateFiles = new StateFiles(dirs.getJobDir(id));
|
||||||
|
|
||||||
|
updateState(id, JobState.KILLED);
|
||||||
|
stateFiles.writeFinishedAt(Instant.now());
|
||||||
|
if (error != null) {
|
||||||
|
stateFiles.writeError(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
LOG.info("Job {} killed: {}", id, error);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Schedules a job for retry.
|
* Schedules a job for retry.
|
||||||
*
|
*
|
||||||
|
|||||||
@@ -13,20 +13,22 @@ import com.samsonmedia.barn.state.JobState;
|
|||||||
* <p>Valid transitions:
|
* <p>Valid transitions:
|
||||||
* <ul>
|
* <ul>
|
||||||
* <li>QUEUED → RUNNING, FAILED, CANCELED</li>
|
* <li>QUEUED → RUNNING, FAILED, CANCELED</li>
|
||||||
* <li>RUNNING → SUCCEEDED, FAILED, CANCELED</li>
|
* <li>RUNNING → SUCCEEDED, FAILED, CANCELED, KILLED</li>
|
||||||
* <li>FAILED → QUEUED (for retry)</li>
|
* <li>FAILED → QUEUED (for retry)</li>
|
||||||
* <li>SUCCEEDED → (none, terminal)</li>
|
* <li>SUCCEEDED → (none, terminal)</li>
|
||||||
* <li>CANCELED → (none, terminal)</li>
|
* <li>CANCELED → (none, terminal)</li>
|
||||||
|
* <li>KILLED → QUEUED (for retry)</li>
|
||||||
* </ul>
|
* </ul>
|
||||||
*/
|
*/
|
||||||
public final class JobStateMachine {
|
public final class JobStateMachine {
|
||||||
|
|
||||||
private static final Map<JobState, Set<JobState>> VALID_TRANSITIONS = Map.of(
|
private static final Map<JobState, Set<JobState>> VALID_TRANSITIONS = Map.of(
|
||||||
JobState.QUEUED, Set.of(JobState.RUNNING, JobState.FAILED, JobState.CANCELED),
|
JobState.QUEUED, Set.of(JobState.RUNNING, JobState.FAILED, JobState.CANCELED),
|
||||||
JobState.RUNNING, Set.of(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED),
|
JobState.RUNNING, Set.of(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED, JobState.KILLED),
|
||||||
JobState.FAILED, Set.of(JobState.QUEUED), // For retry
|
JobState.FAILED, Set.of(JobState.QUEUED), // For retry
|
||||||
JobState.SUCCEEDED, Set.of(),
|
JobState.SUCCEEDED, Set.of(),
|
||||||
JobState.CANCELED, Set.of()
|
JobState.CANCELED, Set.of(),
|
||||||
|
JobState.KILLED, Set.of(JobState.QUEUED) // For retry
|
||||||
);
|
);
|
||||||
|
|
||||||
private JobStateMachine() {
|
private JobStateMachine() {
|
||||||
|
|||||||
@@ -69,7 +69,7 @@ public class BarnService {
|
|||||||
|
|
||||||
Duration heartbeatThreshold = Duration.ofSeconds(config.service().staleHeartbeatThresholdSeconds());
|
Duration heartbeatThreshold = Duration.ofSeconds(config.service().staleHeartbeatThresholdSeconds());
|
||||||
HeartbeatChecker heartbeatChecker = new HeartbeatChecker(heartbeatThreshold);
|
HeartbeatChecker heartbeatChecker = new HeartbeatChecker(heartbeatThreshold);
|
||||||
this.crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs);
|
this.crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs, config);
|
||||||
|
|
||||||
this.shutdownLatch = new CountDownLatch(1);
|
this.shutdownLatch = new CountDownLatch(1);
|
||||||
this.running = new AtomicBoolean(false);
|
this.running = new AtomicBoolean(false);
|
||||||
|
|||||||
@@ -17,7 +17,10 @@ public enum JobState {
|
|||||||
FAILED,
|
FAILED,
|
||||||
|
|
||||||
/** Job was manually canceled. */
|
/** Job was manually canceled. */
|
||||||
CANCELED;
|
CANCELED,
|
||||||
|
|
||||||
|
/** Job was killed when the service was terminated unexpectedly. */
|
||||||
|
KILLED;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Parses a job state from a string (case-insensitive).
|
* Parses a job state from a string (case-insensitive).
|
||||||
@@ -33,8 +36,8 @@ public enum JobState {
|
|||||||
try {
|
try {
|
||||||
return valueOf(value.trim().toUpperCase());
|
return valueOf(value.trim().toUpperCase());
|
||||||
} catch (IllegalArgumentException e) {
|
} catch (IllegalArgumentException e) {
|
||||||
throw new IllegalArgumentException(
|
throw new IllegalArgumentException("Invalid job state: '" + value
|
||||||
"Invalid job state: '" + value + "'. Valid values are: queued, running, succeeded, failed, canceled");
|
+ "'. Valid values are: queued, running, succeeded, failed, canceled, killed");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,7 +56,7 @@ public enum JobState {
|
|||||||
* @return true if the job is in a terminal state
|
* @return true if the job is in a terminal state
|
||||||
*/
|
*/
|
||||||
public boolean isTerminal() {
|
public boolean isTerminal() {
|
||||||
return this == SUCCEEDED || this == FAILED || this == CANCELED;
|
return this == SUCCEEDED || this == FAILED || this == CANCELED || this == KILLED;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import org.junit.jupiter.api.Nested;
|
|||||||
import org.junit.jupiter.api.Test;
|
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.Config;
|
||||||
import com.samsonmedia.barn.config.JobsConfig;
|
import com.samsonmedia.barn.config.JobsConfig;
|
||||||
import com.samsonmedia.barn.jobs.Job;
|
import com.samsonmedia.barn.jobs.Job;
|
||||||
import com.samsonmedia.barn.jobs.JobRepository;
|
import com.samsonmedia.barn.jobs.JobRepository;
|
||||||
@@ -33,7 +34,8 @@ class CrashRecoveryTest {
|
|||||||
private JobRepository repository;
|
private JobRepository repository;
|
||||||
private HeartbeatChecker heartbeatChecker;
|
private HeartbeatChecker heartbeatChecker;
|
||||||
private CrashRecovery crashRecovery;
|
private CrashRecovery crashRecovery;
|
||||||
private JobsConfig config;
|
private JobsConfig jobsConfig;
|
||||||
|
private Config config;
|
||||||
|
|
||||||
@BeforeEach
|
@BeforeEach
|
||||||
void setUp() throws IOException {
|
void setUp() throws IOException {
|
||||||
@@ -41,8 +43,9 @@ class CrashRecoveryTest {
|
|||||||
dirs.initialize();
|
dirs.initialize();
|
||||||
repository = new JobRepository(dirs);
|
repository = new JobRepository(dirs);
|
||||||
heartbeatChecker = new HeartbeatChecker(Duration.ofSeconds(30));
|
heartbeatChecker = new HeartbeatChecker(Duration.ofSeconds(30));
|
||||||
crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs);
|
config = Config.withDefaults();
|
||||||
config = JobsConfig.withDefaults();
|
crashRecovery = new CrashRecovery(repository, heartbeatChecker, dirs, config);
|
||||||
|
jobsConfig = JobsConfig.withDefaults();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nested
|
@Nested
|
||||||
@@ -50,19 +53,25 @@ class CrashRecoveryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void constructor_withNullRepository_shouldThrowException() {
|
void constructor_withNullRepository_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new CrashRecovery(null, heartbeatChecker, dirs))
|
assertThatThrownBy(() -> new CrashRecovery(null, heartbeatChecker, dirs, config))
|
||||||
.isInstanceOf(NullPointerException.class);
|
.isInstanceOf(NullPointerException.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void constructor_withNullHeartbeatChecker_shouldThrowException() {
|
void constructor_withNullHeartbeatChecker_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new CrashRecovery(repository, null, dirs))
|
assertThatThrownBy(() -> new CrashRecovery(repository, null, dirs, config))
|
||||||
.isInstanceOf(NullPointerException.class);
|
.isInstanceOf(NullPointerException.class);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void constructor_withNullDirs_shouldThrowException() {
|
void constructor_withNullDirs_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> new CrashRecovery(repository, heartbeatChecker, null))
|
assertThatThrownBy(() -> new CrashRecovery(repository, heartbeatChecker, null, config))
|
||||||
|
.isInstanceOf(NullPointerException.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void constructor_withNullConfig_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() -> new CrashRecovery(repository, heartbeatChecker, dirs, null))
|
||||||
.isInstanceOf(NullPointerException.class);
|
.isInstanceOf(NullPointerException.class);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -79,7 +88,7 @@ class CrashRecoveryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recoverOrphanedJobs_withQueuedJobs_shouldNotRecover() throws IOException {
|
void recoverOrphanedJobs_withQueuedJobs_shouldNotRecover() throws IOException {
|
||||||
repository.create(List.of("echo", "test"), "test", config);
|
repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||||
|
|
||||||
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
List<Job> recovered = crashRecovery.recoverOrphanedJobs();
|
||||||
|
|
||||||
@@ -88,7 +97,7 @@ class CrashRecoveryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recoverOrphanedJobs_withCompletedJobs_shouldNotRecover() throws IOException {
|
void recoverOrphanedJobs_withCompletedJobs_shouldNotRecover() throws IOException {
|
||||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||||
repository.markStarted(job.id(), 12345);
|
repository.markStarted(job.id(), 12345);
|
||||||
repository.markCompleted(job.id(), 0, null);
|
repository.markCompleted(job.id(), 0, null);
|
||||||
|
|
||||||
@@ -99,7 +108,7 @@ class CrashRecoveryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recoverOrphanedJobs_withRunningJobFreshHeartbeat_shouldNotRecover() throws IOException {
|
void recoverOrphanedJobs_withRunningJobFreshHeartbeat_shouldNotRecover() throws IOException {
|
||||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||||
repository.markStarted(job.id(), ProcessUtils.getCurrentPid()); // Use current PID (alive)
|
repository.markStarted(job.id(), ProcessUtils.getCurrentPid()); // Use current PID (alive)
|
||||||
repository.updateHeartbeat(job.id(), Instant.now()); // Fresh heartbeat
|
repository.updateHeartbeat(job.id(), Instant.now()); // Fresh heartbeat
|
||||||
|
|
||||||
@@ -110,7 +119,7 @@ class CrashRecoveryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recoverOrphanedJobs_withRunningJobStaleHeartbeatDeadProcess_shouldRecover() throws IOException {
|
void recoverOrphanedJobs_withRunningJobStaleHeartbeatDeadProcess_shouldRecover() throws IOException {
|
||||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||||
// Use a PID that's unlikely to exist (very high number)
|
// Use a PID that's unlikely to exist (very high number)
|
||||||
repository.markStarted(job.id(), 999999999L);
|
repository.markStarted(job.id(), 999999999L);
|
||||||
// Set a stale heartbeat
|
// Set a stale heartbeat
|
||||||
@@ -121,15 +130,15 @@ class CrashRecoveryTest {
|
|||||||
assertThat(recovered).hasSize(1);
|
assertThat(recovered).hasSize(1);
|
||||||
assertThat(recovered.get(0).id()).isEqualTo(job.id());
|
assertThat(recovered.get(0).id()).isEqualTo(job.id());
|
||||||
|
|
||||||
// Verify job is now marked as failed
|
// Verify job was killed and auto-retried (state is QUEUED with retry count incremented)
|
||||||
Job updatedJob = repository.findById(job.id()).orElseThrow();
|
Job updatedJob = repository.findById(job.id()).orElseThrow();
|
||||||
assertThat(updatedJob.state()).isEqualTo(JobState.FAILED);
|
assertThat(updatedJob.state()).isEqualTo(JobState.QUEUED);
|
||||||
assertThat(updatedJob.error()).contains("orphaned");
|
assertThat(updatedJob.retryCount()).isEqualTo(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recoverOrphanedJobs_withRunningJobNoHeartbeatDeadProcess_shouldRecover() throws IOException {
|
void recoverOrphanedJobs_withRunningJobNoHeartbeatDeadProcess_shouldRecover() throws IOException {
|
||||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||||
repository.markStarted(job.id(), 999999999L);
|
repository.markStarted(job.id(), 999999999L);
|
||||||
// Clear heartbeat to simulate crash before first heartbeat
|
// Clear heartbeat to simulate crash before first heartbeat
|
||||||
clearHeartbeat(job.id());
|
clearHeartbeat(job.id());
|
||||||
@@ -142,7 +151,7 @@ class CrashRecoveryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recoverOrphanedJobs_withRunningJobStaleHeartbeatAliveProcess_shouldNotRecover() throws IOException {
|
void recoverOrphanedJobs_withRunningJobStaleHeartbeatAliveProcess_shouldNotRecover() throws IOException {
|
||||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||||
// Use current process PID which is definitely alive
|
// Use current process PID which is definitely alive
|
||||||
repository.markStarted(job.id(), ProcessUtils.getCurrentPid());
|
repository.markStarted(job.id(), ProcessUtils.getCurrentPid());
|
||||||
// Set a stale heartbeat
|
// Set a stale heartbeat
|
||||||
@@ -156,7 +165,7 @@ class CrashRecoveryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recoverOrphanedJobs_withRunningJobNoPid_shouldRecover() throws IOException {
|
void recoverOrphanedJobs_withRunningJobNoPid_shouldRecover() throws IOException {
|
||||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||||
// Manually set running state without PID (simulates partial write)
|
// Manually set running state without PID (simulates partial write)
|
||||||
StateFiles stateFiles = new StateFiles(dirs.getJobDir(job.id()));
|
StateFiles stateFiles = new StateFiles(dirs.getJobDir(job.id()));
|
||||||
stateFiles.writeState(JobState.RUNNING);
|
stateFiles.writeState(JobState.RUNNING);
|
||||||
@@ -171,7 +180,7 @@ class CrashRecoveryTest {
|
|||||||
void recoverOrphanedJobs_withMultipleOrphanedJobs_shouldRecoverAll() throws IOException {
|
void recoverOrphanedJobs_withMultipleOrphanedJobs_shouldRecoverAll() throws IOException {
|
||||||
// Create 3 orphaned jobs
|
// Create 3 orphaned jobs
|
||||||
for (int i = 0; i < 3; i++) {
|
for (int i = 0; i < 3; i++) {
|
||||||
Job job = repository.create(List.of("echo", "test" + i), "test", config);
|
Job job = repository.create(List.of("echo", "test" + i), "test", jobsConfig);
|
||||||
repository.markStarted(job.id(), 999999999L + i);
|
repository.markStarted(job.id(), 999999999L + i);
|
||||||
setStaleHeartbeat(job.id(), Duration.ofMinutes(5));
|
setStaleHeartbeat(job.id(), Duration.ofMinutes(5));
|
||||||
}
|
}
|
||||||
@@ -183,16 +192,41 @@ class CrashRecoveryTest {
|
|||||||
|
|
||||||
@Test
|
@Test
|
||||||
void recoverOrphanedJobs_shouldSetCorrectExitCode() throws IOException {
|
void recoverOrphanedJobs_shouldSetCorrectExitCode() throws IOException {
|
||||||
Job job = repository.create(List.of("echo", "test"), "test", config);
|
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||||
repository.markStarted(job.id(), 999999999L);
|
repository.markStarted(job.id(), 999999999L);
|
||||||
setStaleHeartbeat(job.id(), Duration.ofMinutes(5));
|
setStaleHeartbeat(job.id(), Duration.ofMinutes(5));
|
||||||
|
|
||||||
crashRecovery.recoverOrphanedJobs();
|
crashRecovery.recoverOrphanedJobs();
|
||||||
|
|
||||||
Job updatedJob = repository.findById(job.id()).orElseThrow();
|
Job updatedJob = repository.findById(job.id()).orElseThrow();
|
||||||
// Exit code is stored as symbolic string, so we check error message
|
// Verify the job was killed and auto-retried (state is QUEUED with retry count incremented)
|
||||||
assertThat(updatedJob.error()).contains("orphaned");
|
assertThat(updatedJob.state()).isEqualTo(JobState.QUEUED);
|
||||||
assertThat(updatedJob.finishedAt()).isNotNull();
|
assertThat(updatedJob.retryCount()).isEqualTo(1);
|
||||||
|
assertThat(updatedJob.retryAt()).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void recoverOrphanedJobs_withRetriesExhausted_shouldStayKilled() throws IOException {
|
||||||
|
// Create a config with maxRetries = 0 so no auto-retry
|
||||||
|
Config noRetryConfig = new Config(
|
||||||
|
config.service(),
|
||||||
|
new JobsConfig(config.jobs().defaultTimeoutSeconds(), 0, 1, 1.0, List.of()),
|
||||||
|
config.cleanup(),
|
||||||
|
config.storage()
|
||||||
|
);
|
||||||
|
CrashRecovery noRetryCrashRecovery = new CrashRecovery(
|
||||||
|
repository, heartbeatChecker, dirs, noRetryConfig);
|
||||||
|
|
||||||
|
Job job = repository.create(List.of("echo", "test"), "test", jobsConfig);
|
||||||
|
repository.markStarted(job.id(), 999999999L);
|
||||||
|
setStaleHeartbeat(job.id(), Duration.ofMinutes(5));
|
||||||
|
|
||||||
|
noRetryCrashRecovery.recoverOrphanedJobs();
|
||||||
|
|
||||||
|
Job updatedJob = repository.findById(job.id()).orElseThrow();
|
||||||
|
// With retries disabled, job should stay in KILLED state
|
||||||
|
assertThat(updatedJob.state()).isEqualTo(JobState.KILLED);
|
||||||
|
assertThat(updatedJob.error()).contains("killed");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -227,6 +227,35 @@ class JobRepositoryTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Nested
|
||||||
|
class MarkKilled {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void markKilled_shouldSetKilledState() throws IOException {
|
||||||
|
Job job = repository.create(List.of("echo"), null, config);
|
||||||
|
repository.markStarted(job.id(), 12345L);
|
||||||
|
|
||||||
|
repository.markKilled(job.id(), "Process killed - daemon restarted");
|
||||||
|
|
||||||
|
Job updated = repository.findById(job.id()).orElseThrow();
|
||||||
|
assertThat(updated.state()).isEqualTo(JobState.KILLED);
|
||||||
|
assertThat(updated.error()).isEqualTo("Process killed - daemon restarted");
|
||||||
|
assertThat(updated.finishedAt()).isNotNull();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void markKilled_withNullError_shouldSucceed() throws IOException {
|
||||||
|
Job job = repository.create(List.of("echo"), null, config);
|
||||||
|
repository.markStarted(job.id(), 12345L);
|
||||||
|
|
||||||
|
repository.markKilled(job.id(), null);
|
||||||
|
|
||||||
|
Job updated = repository.findById(job.id()).orElseThrow();
|
||||||
|
assertThat(updated.state()).isEqualTo(JobState.KILLED);
|
||||||
|
assertThat(updated.error()).isNull();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Nested
|
@Nested
|
||||||
class ScheduleRetry {
|
class ScheduleRetry {
|
||||||
|
|
||||||
@@ -244,6 +273,21 @@ class JobRepositoryTest {
|
|||||||
assertThat(updated.retryCount()).isEqualTo(1);
|
assertThat(updated.retryCount()).isEqualTo(1);
|
||||||
assertThat(updated.retryAt()).isEqualTo(retryAt);
|
assertThat(updated.retryAt()).isEqualTo(retryAt);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void scheduleRetry_fromKilledState_shouldTransitionToQueued() throws IOException {
|
||||||
|
Job job = repository.create(List.of("echo"), null, config);
|
||||||
|
repository.markStarted(job.id(), 12345L);
|
||||||
|
repository.markKilled(job.id(), "Daemon restarted");
|
||||||
|
Instant retryAt = Instant.now().plusSeconds(30);
|
||||||
|
|
||||||
|
repository.scheduleRetry(job.id(), retryAt);
|
||||||
|
|
||||||
|
Job updated = repository.findById(job.id()).orElseThrow();
|
||||||
|
assertThat(updated.state()).isEqualTo(JobState.QUEUED);
|
||||||
|
assertThat(updated.retryCount()).isEqualTo(1);
|
||||||
|
assertThat(updated.retryAt()).isEqualTo(retryAt);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@Nested
|
@Nested
|
||||||
|
|||||||
@@ -44,11 +44,28 @@ class JobStateMachineTest {
|
|||||||
JobStateMachine.validateTransition(JobState.RUNNING, JobState.CANCELED);
|
JobStateMachine.validateTransition(JobState.RUNNING, JobState.CANCELED);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void running_toKilled_shouldBeValid() {
|
||||||
|
JobStateMachine.validateTransition(JobState.RUNNING, JobState.KILLED);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void failed_toQueued_shouldBeValid() {
|
void failed_toQueued_shouldBeValid() {
|
||||||
JobStateMachine.validateTransition(JobState.FAILED, JobState.QUEUED);
|
JobStateMachine.validateTransition(JobState.FAILED, JobState.QUEUED);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void killed_toQueued_shouldBeValid() {
|
||||||
|
JobStateMachine.validateTransition(JobState.KILLED, JobState.QUEUED);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void killed_toRunning_shouldThrowException() {
|
||||||
|
assertThatThrownBy(() ->
|
||||||
|
JobStateMachine.validateTransition(JobState.KILLED, JobState.RUNNING))
|
||||||
|
.isInstanceOf(IllegalStateException.class);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void queued_toSucceeded_shouldThrowException() {
|
void queued_toSucceeded_shouldThrowException() {
|
||||||
assertThatThrownBy(() ->
|
assertThatThrownBy(() ->
|
||||||
@@ -111,7 +128,9 @@ class JobStateMachineTest {
|
|||||||
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.SUCCEEDED)).isTrue();
|
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.SUCCEEDED)).isTrue();
|
||||||
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.FAILED)).isTrue();
|
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.FAILED)).isTrue();
|
||||||
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.CANCELED)).isTrue();
|
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.CANCELED)).isTrue();
|
||||||
|
assertThat(JobStateMachine.isValidTransition(JobState.RUNNING, JobState.KILLED)).isTrue();
|
||||||
assertThat(JobStateMachine.isValidTransition(JobState.FAILED, JobState.QUEUED)).isTrue();
|
assertThat(JobStateMachine.isValidTransition(JobState.FAILED, JobState.QUEUED)).isTrue();
|
||||||
|
assertThat(JobStateMachine.isValidTransition(JobState.KILLED, JobState.QUEUED)).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -119,6 +138,7 @@ class JobStateMachineTest {
|
|||||||
assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.SUCCEEDED)).isFalse();
|
assertThat(JobStateMachine.isValidTransition(JobState.QUEUED, JobState.SUCCEEDED)).isFalse();
|
||||||
assertThat(JobStateMachine.isValidTransition(JobState.SUCCEEDED, JobState.QUEUED)).isFalse();
|
assertThat(JobStateMachine.isValidTransition(JobState.SUCCEEDED, JobState.QUEUED)).isFalse();
|
||||||
assertThat(JobStateMachine.isValidTransition(JobState.CANCELED, JobState.RUNNING)).isFalse();
|
assertThat(JobStateMachine.isValidTransition(JobState.CANCELED, JobState.RUNNING)).isFalse();
|
||||||
|
assertThat(JobStateMachine.isValidTransition(JobState.KILLED, JobState.RUNNING)).isFalse();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -138,9 +158,9 @@ class JobStateMachineTest {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void forRunning_shouldReturnSucceededFailedCanceled() {
|
void forRunning_shouldReturnSucceededFailedCanceledKilled() {
|
||||||
assertThat(JobStateMachine.getValidTransitions(JobState.RUNNING))
|
assertThat(JobStateMachine.getValidTransitions(JobState.RUNNING))
|
||||||
.containsExactlyInAnyOrder(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED);
|
.containsExactlyInAnyOrder(JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELED, JobState.KILLED);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -159,6 +179,12 @@ class JobStateMachineTest {
|
|||||||
assertThat(JobStateMachine.getValidTransitions(JobState.CANCELED)).isEmpty();
|
assertThat(JobStateMachine.getValidTransitions(JobState.CANCELED)).isEmpty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
void forKilled_shouldReturnQueued() {
|
||||||
|
assertThat(JobStateMachine.getValidTransitions(JobState.KILLED))
|
||||||
|
.containsExactly(JobState.QUEUED);
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
void withNull_shouldThrowException() {
|
void withNull_shouldThrowException() {
|
||||||
assertThatThrownBy(() -> JobStateMachine.getValidTransitions(null))
|
assertThatThrownBy(() -> JobStateMachine.getValidTransitions(null))
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ class JobStateTest {
|
|||||||
assertThat(JobState.fromString("succeeded")).isEqualTo(JobState.SUCCEEDED);
|
assertThat(JobState.fromString("succeeded")).isEqualTo(JobState.SUCCEEDED);
|
||||||
assertThat(JobState.fromString("failed")).isEqualTo(JobState.FAILED);
|
assertThat(JobState.fromString("failed")).isEqualTo(JobState.FAILED);
|
||||||
assertThat(JobState.fromString("canceled")).isEqualTo(JobState.CANCELED);
|
assertThat(JobState.fromString("canceled")).isEqualTo(JobState.CANCELED);
|
||||||
|
assertThat(JobState.fromString("killed")).isEqualTo(JobState.KILLED);
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -54,7 +55,7 @@ class JobStateTest {
|
|||||||
assertThatThrownBy(() -> JobState.fromString("invalid"))
|
assertThatThrownBy(() -> JobState.fromString("invalid"))
|
||||||
.isInstanceOf(IllegalArgumentException.class)
|
.isInstanceOf(IllegalArgumentException.class)
|
||||||
.hasMessageContaining("Invalid job state")
|
.hasMessageContaining("Invalid job state")
|
||||||
.hasMessageContaining("queued, running, succeeded, failed, canceled");
|
.hasMessageContaining("queued, running, succeeded, failed, canceled, killed");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -64,6 +65,7 @@ class JobStateTest {
|
|||||||
assertThat(JobState.SUCCEEDED.toLowercase()).isEqualTo("succeeded");
|
assertThat(JobState.SUCCEEDED.toLowercase()).isEqualTo("succeeded");
|
||||||
assertThat(JobState.FAILED.toLowercase()).isEqualTo("failed");
|
assertThat(JobState.FAILED.toLowercase()).isEqualTo("failed");
|
||||||
assertThat(JobState.CANCELED.toLowercase()).isEqualTo("canceled");
|
assertThat(JobState.CANCELED.toLowercase()).isEqualTo("canceled");
|
||||||
|
assertThat(JobState.KILLED.toLowercase()).isEqualTo("killed");
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -71,6 +73,7 @@ class JobStateTest {
|
|||||||
assertThat(JobState.SUCCEEDED.isTerminal()).isTrue();
|
assertThat(JobState.SUCCEEDED.isTerminal()).isTrue();
|
||||||
assertThat(JobState.FAILED.isTerminal()).isTrue();
|
assertThat(JobState.FAILED.isTerminal()).isTrue();
|
||||||
assertThat(JobState.CANCELED.isTerminal()).isTrue();
|
assertThat(JobState.CANCELED.isTerminal()).isTrue();
|
||||||
|
assertThat(JobState.KILLED.isTerminal()).isTrue();
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
@@ -90,5 +93,6 @@ class JobStateTest {
|
|||||||
assertThat(JobState.SUCCEEDED.isActive()).isFalse();
|
assertThat(JobState.SUCCEEDED.isActive()).isFalse();
|
||||||
assertThat(JobState.FAILED.isActive()).isFalse();
|
assertThat(JobState.FAILED.isActive()).isFalse();
|
||||||
assertThat(JobState.CANCELED.isActive()).isFalse();
|
assertThat(JobState.CANCELED.isActive()).isFalse();
|
||||||
|
assertThat(JobState.KILLED.isActive()).isFalse();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user