Skip to content

Latest commit

Β 

History

History
265 lines (215 loc) Β· 8.95 KB

File metadata and controls

265 lines (215 loc) Β· 8.95 KB

Ofelia Project Documentation Index

πŸ—οΈ Project Overview

Ofelia is a modern, Go-powered job scheduler for Docker containers that provides a lightweight alternative to traditional cron with container orchestration capabilities.

Key Capabilities

  • Container Job Scheduling: Schedule tasks within running containers or spawn new ones
  • Multiple Job Types: Support for RunJob, ExecJob, LocalJob, ServiceJob, and ComposeJob
  • Dynamic Docker Integration: Auto-discover containers via labels or events
  • Resilient Execution: Built-in retry logic, circuit breakers, and rate limiting
  • Comprehensive Monitoring: Prometheus metrics, structured logging, and health checks
  • Web UI & API: Interactive dashboard for job management and monitoring
  • Security-First Design: Input validation, JWT authentication, and sanitization

πŸ“ Project Structure

ofelia/
β”œβ”€β”€ πŸ“¦ core/               # Core business logic and job execution
β”œβ”€β”€ πŸ–₯️ cli/                # Command-line interface and configuration
β”œβ”€β”€ 🌐 web/                # Web UI and API endpoints
β”œβ”€β”€ πŸ“Š metrics/            # Prometheus metrics collection
β”œβ”€β”€ πŸ“ logging/            # Structured logging system
β”œβ”€β”€ βœ… config/             # Configuration validation and sanitization
β”œβ”€β”€ πŸ”Œ middlewares/        # Job execution middlewares (mail, slack, etc.)
β”œβ”€β”€ πŸ§ͺ test/               # Test utilities and helpers
β”œβ”€β”€ πŸ“š docs/               # Documentation
β”œβ”€β”€ 🎨 static/             # Web UI static assets
└── πŸ’Ό example/            # Example configurations

πŸ”§ Core Components

1. Job System (core/)

Job Types

  • RunJob: Execute commands in new containers
  • ExecJob: Execute commands in existing containers
  • LocalJob: Execute commands on the host
  • ServiceJob: Run as Docker Swarm services
  • ComposeJob: Execute docker-compose operations

Core Infrastructure

2. Configuration (cli/ & config/)

3. Web Interface (web/)

4. Monitoring (metrics/)

  • Prometheus Metrics: Job and system metrics
  • Structured Logging: stdlib log/slog (used directly, no wrapper)

5. Middlewares (middlewares/)

πŸ”„ Execution Flow

graph TD
    A[Scheduler] --> B[Job Trigger]
    B --> C[Context Creation]
    C --> D[Middleware Chain]
    D --> E[Job Execution]
    E --> F{Job Type}
    F -->|RunJob| G[New Container]
    F -->|ExecJob| H[Existing Container]
    F -->|LocalJob| I[Host Command]
    F -->|ServiceJob| J[Swarm Service]
    E --> K[Metrics Recording]
    E --> L[Logging]
    E --> M{Retry Needed?}
    M -->|Yes| N[Retry Logic]
    M -->|No| O[Complete]
Loading

πŸ›‘οΈ Security Features

Input Validation

  • Command injection prevention
  • Path traversal protection
  • SQL/LDAP injection guards
  • Docker image name validation
  • Cron expression validation

Authentication & Authorization

  • JWT-based API authentication
  • Secure token management
  • Session handling
  • CORS protection

Resilience Patterns

  • Circuit Breakers: Prevent cascade failures
  • Rate Limiting: Token bucket algorithm
  • Retry Policies: Exponential backoff with jitter
  • Bulkhead Pattern: Resource isolation

πŸ“Š Metrics & Monitoring

Available Metrics

ofelia_jobs_total              # Total jobs executed
ofelia_jobs_failed_total       # Failed job count
ofelia_jobs_running            # Currently running jobs
ofelia_job_duration_seconds    # Job execution duration histogram
ofelia_docker_operations_total # Docker API operations
ofelia_docker_errors_total     # Docker API errors
ofelia_http_requests_total     # HTTP request count
ofelia_circuit_breaker_*       # Circuit breaker states

Health Endpoints

  • /health/liveness: Service availability
  • /health/readiness: Service readiness
  • /metrics: Prometheus metrics endpoint

πŸ”Œ API Reference

Job Management

  • GET /api/jobs: List all jobs
  • GET /api/job/{name}: Get job details
  • POST /api/job/{name}/run: Trigger job execution
  • PUT /api/job/{name}: Update job configuration
  • DELETE /api/job/{name}: Remove job

Authentication

  • POST /api/login: Authenticate and receive JWT
  • POST /api/refresh: Refresh JWT token
  • POST /api/logout: Invalidate token

πŸš€ Configuration Examples

INI Configuration

[job-local "backup"]
schedule = @daily
command = /usr/local/bin/backup.sh

[job-exec "db-maintenance"]
schedule = 0 2 * * *
container = postgres
command = vacuumdb --all --analyze

[job-run "report-generator"]
schedule = 0 */6 * * *
image = myapp/reporter:latest
command = generate-report --type=daily

Docker Labels

labels:
  ofelia.enabled: "true"
  ofelia.job-exec.db-backup.schedule: "@midnight"
  ofelia.job-exec.db-backup.command: "pg_dump -U postgres mydb"

πŸ§ͺ Testing

Test Coverage Areas

  • Unit tests for all core components
  • Integration tests for Docker operations
  • End-to-end tests for job execution
  • Benchmark tests for performance-critical paths

Running Tests

go test ./...                    # Run all tests
go test -race ./...             # Run with race detector
go test -cover ./...            # Show coverage
go test -bench=. ./core         # Run benchmarks

πŸ“š Package Documentation

Core Packages

  • core: Job execution and scheduling
  • cli: Configuration and CLI commands
  • web: HTTP server and API
  • metrics: Monitoring and observability
  • logging: Structured logging
  • config: Validation and sanitization
  • middlewares: Job execution plugins

Visual Documentation

  • Architecture Diagrams: 8 comprehensive mermaid diagrams
    • Job execution lifecycle (sequence)
    • Configuration precedence (5-layer)
    • Docker integration architecture
    • Middleware chain execution
    • Resilience patterns (circuit breaker, retry, rate limiting)
    • Scheduler state machine
    • Web UI & API flow
    • Component interaction map

Practical Guides

  • Integration Patterns: Real-world integration scenarios

    • Database management (backups, maintenance)
    • Log management and archiving
    • Backup & recovery strategies
    • Health monitoring patterns
    • Data synchronization
    • Cleanup & maintenance
    • CI/CD integration
    • Multi-environment patterns
    • Performance optimization
    • Security patterns
  • Quick Reference: Fast-lookup cheat sheet

    • CLI commands
    • Cron schedule formats
    • All job types with examples
    • Docker labels format
    • API endpoints
    • Troubleshooting quick fixes
    • Common patterns
    • Security checklist

πŸ”— Cross-References

Configuration Flow

cli/config.go β†’ config/validator.go β†’ config/sanitizer.go β†’ core/scheduler.go

Job Execution Path

core/scheduler.go β†’ core/context.go β†’ middlewares/* β†’ core/*job.go

Docker Integration

core/docker_client.go ← core/container_monitor.go ← core/runjob.go

Monitoring Pipeline

core/resilient_job.go β†’ metrics/prometheus.go ← web/server.go

πŸ” Quick Navigation


Last Updated: 2025-11-21 | Enhanced with architecture diagrams, integration patterns, and quick reference