core

package
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2026 License: MIT Imports: 35 Imported by: 0

Documentation

Overview

Package core holds the scheduler and the job types it runs: ExecJob (in a running container), RunJob (in a fresh container), RunServiceJob (as a Swarm service) and LocalJob (on the host). Docker access goes through the port interfaces in core/ports so the scheduler stays independent of the SDK.

Index

Constants

View Source
const (
	AnnotationKeyJobName       = "ofelia.job.name"
	AnnotationKeyJobType       = "ofelia.job.type"
	AnnotationKeyExecutionTime = "ofelia.execution.time"
	AnnotationKeySchedulerHost = "ofelia.scheduler.host"
	AnnotationKeyVersion       = "ofelia.version"
)

Default annotation keys that Ofelia attaches to every job execution. These are stable wire-level identifiers consumed by downstream tooling (logging pipelines, dashboards). Don't change without coordinating with consumers.

View Source
const (
	// ExitCodeSwarmError marks a swarm orchestration error (task not found,
	// service unavailable) rather than an exit code reported by a task. It is
	// also the initial value the watcher holds, so it is what remains when the
	// watcher stops before any task reached a terminal state; watchContainer
	// maps it to ErrUnexpected.
	ExitCodeSwarmError = -999
	// ExitCodeTimeout marks max runtime exceeded before task completion. No
	// code path assigns it today — the timeout path returns ErrMaxTimeRunning
	// instead of an exit code.
	ExitCodeTimeout = -998
)

Exit codes for swarm service execution states These are Ofelia-specific codes, not from Docker Swarm API They indicate failure modes that don't map to container exit codes

View Source
const (
	TriggeredSchedule = "@triggered"
	ManualSchedule    = "@manual"
	NoneSchedule      = "@none"

	YearlySchedule   = "@yearly"
	AnnuallySchedule = "@annually" // alias of @yearly
	MonthlySchedule  = "@monthly"
	WeeklySchedule   = "@weekly"
	DailySchedule    = "@daily"
	MidnightSchedule = "@midnight" // alias of @daily
	HourlySchedule   = "@hourly"
)

Special schedule keywords recognized by go-cron and Ofelia.

The time-based keywords (Yearly, Monthly, Weekly, Daily, Hourly and their aliases) map to fixed cron expressions inside go-cron's parser.

The run-on-trigger-only keywords (Triggered, Manual, None) map to a TriggeredSchedule whose Next() returns the zero time, so jobs registered with these schedules never fire automatically — they only run when invoked via TriggerEntryByName() or by another job's on-success/on-failure chain.

View Source
const ComposeExecutionLabel = "ofelia.execution"

ComposeExecutionLabel is the container label a `compose run` job sets to the execution ID, so cleanup can find the run container — and only that one, never a dependency service Compose started alongside it.

View Source
const DefaultStopTimeout = 30 * time.Second

DefaultStopTimeout is the default timeout for graceful shutdown.

View Source
const HashmeTagName = "hash"

HashmeTagName is the struct tag key GetHash inspects. A field takes part in the job hash only when its `hash` tag is set to "true".

View Source
const MinComposeJobsVersion = "5.6.0"

MinComposeJobsVersion is the first docker compose release that understands the top-level `jobs:` section and runs a job with `docker compose run` (Compose 5.6.0). Older releases reject the file before running anything.

Variables

View Source
var (
	// Container errors
	ErrContainerNotFound     = errors.New("container not found")
	ErrContainerStartFailed  = errors.New("failed to start container")
	ErrContainerCreateFailed = errors.New("failed to create container")
	ErrContainerStopFailed   = errors.New("failed to stop container")
	ErrContainerRemoveFailed = errors.New("failed to remove container")

	// Image errors
	ErrImageNotFound      = errors.New("image not found")
	ErrImagePullFailed    = errors.New("failed to pull image")
	ErrLocalImageNotFound = errors.New("local image not found")

	// Service errors
	ErrServiceNotFound     = errors.New("service not found")
	ErrServiceCreateFailed = errors.New("failed to create service")
	ErrServiceStartFailed  = errors.New("failed to start service")
	ErrServiceRemoveFailed = errors.New("failed to remove service")

	// Job errors
	ErrJobNotFound      = errors.New("job not found")
	ErrJobAlreadyExists = errors.New("job already exists")
	ErrJobExecution     = errors.New("job execution failed")
	ErrMaxTimeRunning   = errors.New("max runtime exceeded")
	ErrUnexpected       = errors.New("unexpected error")

	// Workflow errors
	ErrCircularDependency = errors.New("circular dependency detected")
	ErrWorkflowInvalid    = errors.New("invalid workflow configuration")

	// Validation errors
	ErrEmptyCommand         = errors.New("command cannot be empty")
	ErrUnsupportedFieldType = errors.New("unsupported field type")
	ErrImageOrContainer     = errors.New("job-run requires either 'image' or 'container'")
	ErrImageRequired        = errors.New("job-service-run requires 'image' to create a new swarm service")
	ErrInvalidVolume        = errors.New("invalid volume: expected source:target[:ro|rw]")
	ErrMaxRuntimeNegative   = errors.New("max-runtime must not be negative")

	// Scheduler errors
	ErrSchedulerTimeout        = errors.New("scheduler stop timed out")
	ErrConcurrencyLimitReached = errors.New("max concurrent jobs limit reached")

	// Shutdown errors
	ErrShutdownInProgress = errors.New("shutdown already in progress")
	ErrShutdownTimeout    = errors.New("shutdown timed out")
	ErrJobCanceled        = errors.New("job canceled: shutdown in progress")
	ErrCannotStartJob     = errors.New("cannot start job during shutdown")
	ErrWaitTimeout        = errors.New("timeout waiting for jobs to complete")

	// Resilience errors
	ErrCircuitBreakerOpen     = errors.New("circuit breaker is open")
	ErrCircuitBreakerHalfOpen = errors.New("circuit breaker is half-open but max calls reached")
	ErrCircuitBreakerUnknown  = errors.New("circuit breaker is in unknown state")
	ErrRateLimitExceeded      = errors.New("rate limit exceeded")
	ErrTokensExceedCapacity   = errors.New("requested tokens exceed capacity")
	ErrBulkheadFull           = errors.New("bulkhead is full")

	// Docker SDK errors
	ErrResponseChannelClosed = errors.New("response channel closed unexpectedly")
)

Common errors used across the package

View Source
var (
	ErrExecStillRunning   = domain.ErrExecStillRunning
	ErrExecOutcomeUnknown = domain.ErrExecOutcomeUnknown
)

ErrExecStillRunning and ErrExecOutcomeUnknown classify a canceled job-exec execution; see ExecJob.Run.

View Source
var (
	// ErrEmptyScheduler was returned by Start when it was called with no jobs
	// registered. Start now accepts an empty scheduler, so nothing returns
	// this error; it is retained for API compatibility.
	ErrEmptyScheduler = errors.New("unable to start an empty scheduler")
	// ErrEmptySchedule is returned by AddJob and AddJobWithTags when the job's
	// schedule string is empty. Jobs meant to run only on demand must use
	// @triggered, @manual or @none rather than an empty schedule.
	ErrEmptySchedule = errors.New("unable to add a job with an empty schedule")
)
View Source
var (
	// DefaultBufferPool provides enhanced performance for job execution
	// This replaces the simple buffer pool with multi-tier adaptive pooling
	// Note: ShrinkInterval is set to 0 to prevent background goroutine at package init
	DefaultBufferPool = func() *EnhancedBufferPool {
		cfg := DefaultEnhancedBufferPoolConfig()
		cfg.ShrinkInterval = 0
		cfg.EnablePrewarming = false
		cfg.PoolSize = 0
		return NewEnhancedBufferPool(cfg, nil)
	}()
)

Global enhanced buffer pool instance

View Source
var ErrComposeExecMaxRuntime = errors.New("max-runtime is not supported with exec = true")

ErrComposeExecMaxRuntime rejects max-runtime on a compose job in exec mode: the command runs inside an existing container and cannot be stopped from outside, so the bound would end only Ofelia's wait, not the command.

View Source
var ErrComposeJobsUnsupported = errors.New("docker compose CLI cannot run compose jobs")

ErrComposeJobsUnsupported reports that the docker compose CLI Ofelia would run Compose jobs with is missing or older than MinComposeJobsVersion.

View Source
var ErrComposeTerminationUnconfirmed = errors.New("compose run termination unconfirmed")

ErrComposeTerminationUnconfirmed reports that a run container may still be running after cancellation or an abnormal CLI exit: Ofelia stopped waiting, but could not confirm through Docker that the container is gone.

View Source
var ErrJobBusy = errors.New("job is busy")

ErrJobBusy is returned by RunJob for a job with durable schedule state while a run of it is in progress or waiting for a global slot (ADR-005), and for any job while the canceled run of a removed or replaced job of the same name is still stopping (runGate).

View Source
var ErrLocalTerminationUnconfirmed = errors.New("local job termination unconfirmed")

ErrLocalTerminationUnconfirmed reports that a canceled local job may still be running: its process (group) was still present after SIGKILL, typically because a process changed credentials and Ofelia may not signal it.

View Source
var ErrNilContainerInspector = errors.New("container inspector is nil")

ErrNilContainerInspector is returned when ResolveEnvFrom is called with a nil provider.

View Source
var ErrSkippedExecution = errors.New("skipped execution")

ErrSkippedExecution pass this error to `Execution.Stop` if you wish to mark it as skipped.

View Source
var GlobalPerformanceMetrics = NewPerformanceMetrics()

GlobalPerformanceMetrics is the process-wide PerformanceMetrics instance, created at package initialization for callers that have no recorder injected. Its counters are shared by every user of the package, so Reset affects all of them.

View Source
var Version = "dev"

Version is the Ofelia version, set via ldflags during build. Defaults to "dev" if not set.

Functions

func BuildWorkflowDependencies added in v0.21.0

func BuildWorkflowDependencies(cronInstance *cron.Cron, jobs []Job, logger *slog.Logger) error

BuildWorkflowDependencies analyzes job dependency configuration and wires dependency edges into the go-cron scheduler using AddDependencyByName.

Mapping from ofelia config to go-cron trigger conditions:

  • depends-on: child.After(parent, OnSuccess) -- wait for parent to succeed
  • on-success: target.After(source, OnSuccess) -- trigger target when source succeeds
  • on-failure: target.After(source, OnFailure) -- trigger target when source fails

go-cron handles cycle detection, execution ordering, and status tracking natively.

func CheckComposeJobsSupport added in v1.1.0

func CheckComposeJobsSupport(ctx context.Context) error

CheckComposeJobsSupport returns an error wrapping ErrComposeJobsUnsupported when the docker compose CLI is missing or older than MinComposeJobsVersion, naming the version it found.

func ComposeCLIVersion added in v1.1.0

func ComposeCLIVersion(ctx context.Context) (string, error)

ComposeCLIVersion returns the version `docker compose version --short` reports, run with the same Docker endpoint as a compose job (see composeChildEnv), without a leading "v".

func ComposeVersionAtLeast added in v1.1.0

func ComposeVersionAtLeast(version, minimum string) bool

ComposeVersionAtLeast reports whether version is min or later, comparing the numeric major, minor and patch parts. A pre-release or build suffix is ignored, and a version that does not parse counts as older.

func GetHash added in v0.10.1

func GetHash(t reflect.Type, v reflect.Value, hash *string) error

GetHash walks the fields of struct type t, taking values from v, and appends a stable string form of every field tagged `hash:"true"` to *hash. Nested struct fields are recursed into and contribute their own tagged fields. The result is a concatenation used to detect configuration changes, not a cryptographic digest — do not treat it as one.

v must be the struct value matching t and hash must be non-nil; GetHash appends to whatever is already there. It returns ErrUnsupportedFieldType for a tagged field whose kind it cannot represent — supported kinds are string, the signed and unsigned integer kinds, bool, string slices, and pointer to string.

func IsNonZeroExitError added in v0.10.1

func IsNonZeroExitError(err error) bool

IsNonZeroExitError checks if the error is a non-zero exit code error

func IsRetryableError added in v0.10.1

func IsRetryableError(err error) bool

IsRetryableError checks if an error should trigger a retry

func IsTriggeredSchedule added in v0.14.0

func IsTriggeredSchedule(schedule string) bool

IsTriggeredSchedule returns true if the schedule string indicates the job should only run when triggered (not on a time-based schedule). This is a convenience wrapper around string comparison for the three recognized keywords. See schedule_keywords.go for the full list of recognized schedule strings.

func MergeEnvironments added in v0.23.0

func MergeEnvironments(envFiles, envFrom, explicit []string) []string

MergeEnvironments merges environment variable sources with last-wins semantics. Order: envFiles -> envFrom -> explicit environment.

func ParseEnvFile added in v0.23.0

func ParseEnvFile(path string) ([]string, error)

ParseEnvFile reads an env file and returns KEY=VALUE pairs. Skips blank lines, lines starting with #, and lines without =. Strips optional "export " prefix and surrounding quotes from values.

func ParseMaxRuntime added in v1.0.0

func ParseMaxRuntime(s string) (time.Duration, error)

ParseMaxRuntime parses a `max-runtime` duration string into the value RunJob.MaxRuntime carries.

Its callers are the two paths that build a run job from untyped input: web.newRunJobFromRequest, for the API's `maxRuntime` field, and cli.buildPersistedRunJob, for the same value coming back out of the state file. One parser for both keeps them from drifting apart the way the API and state-file paths once disagreed on RunJob.Delete (PR #745). The `[job-run]` config section and Docker labels do NOT come through here — gcfg and mapstructure decode `max-runtime` into the field directly.

An empty string returns a zero Duration, meaning "no per-job override"; callers wire that straight into RunJob.MaxRuntime, whose own zero value already carries that same meaning (see GetMaxRuntime). "0s" parses to the same zero and therefore means the same thing — it does not mean "unlimited".

func ResolveEnvFrom added in v0.23.0

func ResolveEnvFrom(ctx context.Context, provider ContainerInspector, containerName string) ([]string, error)

ResolveEnvFrom inspects a running Docker container and returns its env vars.

func ResolveJobEnvironment added in v0.23.0

func ResolveJobEnvironment(
	ctx context.Context,
	envFiles, envFrom, explicit []string,
	provider ContainerInspector,
	warnFn func(string),
) ([]string, error)

ResolveJobEnvironment resolves env-file and env-from sources, merging with explicit environment. If provider is nil, env-from entries are skipped with a warning via warnFn. Returns the merged []string in KEY=VALUE format. Does NOT mutate input slices.

func Retry added in v0.10.1

func Retry(ctx context.Context, policy *RetryPolicy, fn func() error) error

Retry executes a function with retry logic

func ScheduleRevision added in v1.1.0

func ScheduleRevision(schedule string, catchUp, queue bool) string

ScheduleRevision returns the revision of a schedule: its expression (which carries CRON_TZ for an explicit zone), the scheduler's local zone when it names none, and both policies.

func SetDefaultClock added in v0.17.0

func SetDefaultClock(c Clock)

SetDefaultClock replaces the process-wide clock returned by GetDefaultClock. It is not safe for concurrent use: call it from a test before any scheduler is created and restore the previous clock afterwards.

func SetGlobalBufferPoolLogger added in v0.11.0

func SetGlobalBufferPoolLogger(logger *slog.Logger)

SetGlobalBufferPoolLogger sets the logger for the global buffer pool

func WrapContainerError added in v0.10.1

func WrapContainerError(op string, containerID string, err error) error

WrapContainerError wraps a container-related error with context

func WrapImageError added in v0.10.1

func WrapImageError(op string, image string, err error) error

WrapImageError wraps an image-related error with context

func WrapJobError added in v0.10.1

func WrapJobError(op string, jobName string, err error) error

WrapJobError wraps a job-related error with context

func WrapServiceError added in v0.10.1

func WrapServiceError(op string, serviceID string, err error) error

WrapServiceError wraps a service-related error with context

Types

type BareJob

type BareJob struct {
	Schedule string `hash:"true"`
	Name     string `hash:"true"`
	Command  string `hash:"true"`
	// RunOnStartup controls whether the job is executed once immediately when the scheduler starts,
	// before regular cron-based scheduling begins. This is a boolean flag with a default value of false.
	// Startup executions are dispatched in non-blocking goroutines so they do not delay scheduler startup.
	RunOnStartup     bool     `default:"false" gcfg:"run-on-startup" mapstructure:"run-on-startup" hash:"true"`
	HistoryLimit     int      `default:"10"`
	MaxRetries       int      `default:"0"`                                  // Maximum number of retry attempts (0 = no retries)
	RetryDelayMs     int      `default:"1000"`                               // Initial retry delay in milliseconds
	RetryExponential bool     `default:"true"`                               // Use exponential backoff for retries
	RetryMaxDelayMs  int      `default:"60000"`                              // Maximum retry delay in milliseconds (1 minute)
	Dependencies     []string `gcfg:"depends-on" mapstructure:"depends-on,"` // Jobs that must complete first
	OnSuccess        []string `gcfg:"on-success" mapstructure:"on-success,"` // Jobs to trigger on success
	OnFailure        []string `gcfg:"on-failure" mapstructure:"on-failure,"` // Jobs to trigger on failure
	AllowParallel    bool     `default:"true"`                               // Allow job to run in parallel with others
	// contains filtered or unexported fields
}

BareJob is the base type embedded by every job implementation (ExecJob, RunJob, RunServiceJob, LocalJob, ComposeJob). It holds the fields the scheduler reads — name, schedule, command, retry and dependency settings — together with the middleware chain, the in-flight counter and a bounded execution history, and supplies all of the Job interface except Run through promoted methods. Embedders override Run to do the actual work.

Field defaults come from the `default` struct tags applied during config parsing. On a hand-built value HistoryLimit is 0, which keeps the history unbounded.

func (*BareJob) GetCommand

func (j *BareJob) GetCommand() string

GetCommand returns the configured command string. BareJob does not interpret it — that is up to the embedding job type; the scheduler only uses it for log messages and as part of the change-detection hash.

func (*BareJob) GetCronJobID

func (j *BareJob) GetCronJobID() uint64

GetCronJobID returns the go-cron entry ID assigned when the job was registered, or 0 if it has not been added to a scheduler yet.

func (*BareJob) GetDependencies added in v0.21.2

func (j *BareJob) GetDependencies() []string

GetDependencies returns the list of job names this job depends on.

func (*BareJob) GetHistory added in v0.8.0

func (j *BareJob) GetHistory() []*Execution

GetHistory returns a copy of the job's execution history.

func (*BareJob) GetLastRun added in v0.8.0

func (j *BareJob) GetLastRun() *Execution

GetLastRun returns the last execution of the job, if any.

func (*BareJob) GetName

func (j *BareJob) GetName() string

GetName returns the job's configured name. The name is the scheduler's primary key: go-cron entry registration, lookup, removal, enable/disable and manual triggering all address a job by it.

func (*BareJob) GetOnFailure added in v0.21.2

func (j *BareJob) GetOnFailure() []string

GetOnFailure returns the list of job names to trigger when this job fails.

func (*BareJob) GetOnSuccess added in v0.21.2

func (j *BareJob) GetOnSuccess() []string

GetOnSuccess returns the list of job names to trigger when this job succeeds.

func (*BareJob) GetRetryConfig added in v0.10.1

func (j *BareJob) GetRetryConfig() RetryConfig

GetRetryConfig returns the retry configuration for the job

func (*BareJob) GetSchedule

func (j *BareJob) GetSchedule() string

GetSchedule returns the raw cron expression or keyword the job was configured with, unparsed. Scheduler.AddJobWithTags rejects an empty schedule; the @triggered, @manual and @none keywords register an entry that never fires on its own (see IsTriggeredSchedule).

func (*BareJob) Hash

func (j *BareJob) Hash() (string, error)

Hash returns a change-detection key over the job's `hash:"true"` fields — schedule, name, command and run-on-startup — so a reload can tell whether a job definition actually changed. It is a plain concatenation produced by GetHash, not a cryptographic digest, and returns an error if a tagged field has a type GetHash cannot represent. Every job type with fields of its own overrides this method so those fields count too: ExecJob, LocalJob, ComposeJob and RunServiceJob in job_hash.go, RunJob via RunJobConfig.Hash.

func (*BareJob) Middlewares

func (c *BareJob) Middlewares() []Middleware

func (*BareJob) NotifyStart

func (j *BareJob) NotifyStart()

NotifyStart increments the in-flight counter. Context.Start calls it when an execution begins; every call must be paired with a NotifyStop or Running will never return to zero. Safe for concurrent use.

func (*BareJob) NotifyStop

func (j *BareJob) NotifyStop()

NotifyStop decrements the in-flight counter. Context.Stop calls it once the execution has finished. Safe for concurrent use.

func (*BareJob) ResetMiddlewares added in v0.9.0

func (c *BareJob) ResetMiddlewares(ms ...Middleware)

func (*BareJob) Run added in v0.10.1

func (j *BareJob) Run(ctx *Context) error

Run implements the Job interface - this is handled by jobWrapper

func (*BareJob) Running

func (j *BareJob) Running() int32

Running returns the number of invocations currently in flight, as maintained by NotifyStart and NotifyStop. Safe for concurrent use.

func (*BareJob) SetCronJobID

func (j *BareJob) SetCronJobID(id uint64)

SetCronJobID records the go-cron entry ID for the job. Scheduler.AddJobWithTags calls it right after registration. It is not synchronized, so it must not be called while the job is scheduled.

func (*BareJob) SetLastRun added in v0.8.0

func (j *BareJob) SetLastRun(e *Execution)

SetLastRun stores the last executed run for the job.

func (*BareJob) ShouldRunOnStartup added in v0.18.0

func (j *BareJob) ShouldRunOnStartup() bool

ShouldRunOnStartup returns true if the job should run immediately when the scheduler starts.

func (*BareJob) Use

func (c *BareJob) Use(ms ...Middleware)

type Bulkhead added in v0.10.1

type Bulkhead struct {
	// contains filtered or unexported fields
}

Bulkhead implements the bulkhead pattern for resource isolation

func NewBulkhead added in v0.10.1

func NewBulkhead(name string, maxConcurrent int) *Bulkhead

NewBulkhead creates a new bulkhead

func (*Bulkhead) Execute added in v0.10.1

func (b *Bulkhead) Execute(ctx context.Context, fn func() error) error

Execute runs a function with bulkhead protection

func (*Bulkhead) GetMetrics added in v0.10.1

func (b *Bulkhead) GetMetrics() map[string]any

GetMetrics returns bulkhead metrics

type CircuitBreaker added in v0.10.1

type CircuitBreaker struct {
	// contains filtered or unexported fields
}

CircuitBreaker implements the circuit breaker pattern

func NewCircuitBreaker added in v0.10.1

func NewCircuitBreaker(name string, maxFailures uint32, resetTimeout time.Duration) *CircuitBreaker

NewCircuitBreaker creates a new circuit breaker

func (*CircuitBreaker) Execute added in v0.10.1

func (cb *CircuitBreaker) Execute(fn func() error) error

Execute runs a function through the circuit breaker

func (*CircuitBreaker) GetMetrics added in v0.10.1

func (cb *CircuitBreaker) GetMetrics() map[string]any

GetMetrics returns circuit breaker metrics

func (*CircuitBreaker) GetState added in v0.10.1

func (cb *CircuitBreaker) GetState() CircuitBreakerState

GetState returns the current state of the circuit breaker

type CircuitBreakerState added in v0.10.1

type CircuitBreakerState int

CircuitBreakerState represents the state of a circuit breaker

const (
	// StateClosed passes every call through; a success clears the failure count.
	StateClosed CircuitBreakerState = iota
	// StateOpen rejects calls with ErrCircuitBreakerOpen until resetTimeout has
	// elapsed since the last failure.
	StateOpen
	// StateHalfOpen admits up to halfOpenMaxCalls trial calls, rejecting the rest
	// with ErrCircuitBreakerHalfOpen; a success closes the breaker, a failure
	// reopens it.
	StateHalfOpen
)

The states a CircuitBreaker moves through: it starts closed, opens once maxFailures consecutive failures have been recorded, and after resetTimeout admits trial calls in half-open before closing or opening again.

func (CircuitBreakerState) String added in v0.10.1

func (s CircuitBreakerState) String() string

type Clock added in v0.17.0

type Clock interface {
	Now() time.Time
	NewTicker(d time.Duration) Ticker
	NewTimer(d time.Duration) Timer
	After(d time.Duration) <-chan time.Time
	Sleep(d time.Duration)
}

Clock abstracts the parts of the time package that scheduling code depends on, so tests can drive it with a FakeClock instead of waiting in real time. Durations have the same meaning as in their time package counterparts.

func GetDefaultClock added in v0.17.0

func GetDefaultClock() Clock

GetDefaultClock returns the clock used by schedulers that are created without an explicit one. It is a real clock unless SetDefaultClock replaced it.

func NewRealClock added in v0.17.0

func NewRealClock() Clock

NewRealClock returns a Clock backed directly by the time package.

type ComposeExecutionSnapshot added in v1.1.0

type ComposeExecutionSnapshot struct {
	Model       string                                `json:"-"`
	Files       map[string]domain.ComposeSnapshotFile `json:"-"`
	Environment map[string]string                     `json:"-"`
}

ComposeExecutionSnapshot is an accepted execution model and its captured file inputs. It can contain resolved secrets and must not be serialized to an API response, logged, or written to the schedule state file.

type ComposeJob added in v0.9.0

type ComposeJob struct {
	BareJob  `mapstructure:",squash"`
	Provider DockerProvider `json:"-"`
	File     string         `default:"compose.yml" gcfg:"file" mapstructure:"file" hash:"true"`
	Service  string         `gcfg:"service" mapstructure:"service" hash:"true"`
	Exec     bool           `default:"false" gcfg:"exec" mapstructure:"exec" hash:"true"`
	// MaxRuntime bounds a run-mode execution like RunJob.MaxRuntime: when it
	// expires, the run container is stopped and removed. Zero means no
	// per-job value; the run then follows the scheduler's current
	// [global] max-runtime.
	// Not supported with Exec (see CheckMaxRuntime).
	MaxRuntime time.Duration `gcfg:"max-runtime" mapstructure:"max-runtime" hash:"true"`
	// Project is set only for jobs loaded from a registered Compose project
	// ([compose-project] in the INI, see ADR-004). It cannot be set on a
	// [job-compose] section: the project context lives in the registration.
	Project ComposeProjectContext `mapstructure:"-"`
}

ComposeJob runs a command through the `docker compose` CLI on the host Ofelia itself runs on — `compose run --rm <service>` by default, or `compose exec <service>` when Exec is set. Unlike the other job types it shells out instead of talking to the Docker API, so the docker binary must be on Ofelia's PATH. Provider observes run containers and performs bounded cleanup after cancellation or an abnormal CLI exit.

func NewComposeJob added in v0.9.0

func NewComposeJob() *ComposeJob

NewComposeJob returns an empty ComposeJob; the caller fills in File, Service, Provider and the embedded BareJob.

func (*ComposeJob) CheckMaxRuntime added in v1.1.0

func (j *ComposeJob) CheckMaxRuntime() error

CheckMaxRuntime reports a max-runtime in exec mode, where nothing could enforce it. The job API rejects such a request; a configuration file, which accepted the key before compose jobs honored it, gets a warning instead (see cli), so an existing file keeps loading.

func (*ComposeJob) GetMaxRuntime added in v1.1.0

func (j *ComposeJob) GetMaxRuntime() time.Duration

GetMaxRuntime exposes the per-job maximum runtime so the scheduler bounds the run context with it (MaxRuntimeProvider). Zero leaves the bound to the scheduler: [global] max-runtime in run mode, its 24h default in exec mode.

func (*ComposeJob) Hash added in v0.9.0

func (j *ComposeJob) Hash() (string, error)

Hash returns the change-detection key over every `hash:"true"` field of the compose job, the embedded BareJob fields included.

func (*ComposeJob) InheritsGlobalMaxRuntime added in v1.1.0

func (j *ComposeJob) InheritsGlobalMaxRuntime() bool

InheritsGlobalMaxRuntime reports whether the job runs under `[global] max-runtime` when it has no max-runtime of its own: in run mode it does, in exec mode it does not, because canceling `docker compose exec` does not stop the command (see CheckMaxRuntime).

func (*ComposeJob) Middlewares added in v0.9.0

func (c *ComposeJob) Middlewares() []Middleware

func (*ComposeJob) ResetMiddlewares added in v0.9.0

func (c *ComposeJob) ResetMiddlewares(ms ...Middleware)

func (*ComposeJob) Run added in v0.9.0

func (j *ComposeJob) Run(ctx *Context) error

Run executes the compose command and blocks until the child process exits. File, Service and the parsed command arguments are checked for command injection first, so a malformed job fails before any process is started. Errors cover a rejected argument, a docker binary missing from PATH, and a non-zero exit status. Output is streamed to the execution's stdout/stderr streams.

In run mode the CLI is bound to the run context. Killing the CLI does not stop the container it started, so on cancellation or a max-runtime deadline Run stops the containers labeled with this execution's ID (ComposeExecutionLabel) with a 10s grace period, signals the CLI, removes the labeled containers again after the CLI exited — catching one created while cancellation was in progress — and confirms that none remain. It then returns ErrMaxTimeRunning, wrapped together with ErrComposeTerminationUnconfirmed when the Docker API could not confirm that the run container is gone. An abnormal CLI exit also performs this bounded workload cleanup while preserving the original exit error. If cleanup cannot be confirmed, that error is joined with ErrComposeTerminationUnconfirmed as well.

In exec mode the command runs inside an existing service container. The Docker Engine API has no way to stop an exec'd process from outside (see ExecJob and issue #655), so the child process is not tied to the run context: canceling the run, or the scheduler's default deadline, does not stop it, which is why max-runtime is not honored in exec mode. Enforce a hard limit inside the command (e.g. `timeout 30s ...`).

func (*ComposeJob) SatisfiesRequirement added in v1.1.0

func (j *ComposeJob) SatisfiesRequirement(key string) bool

SatisfiesRequirement reports that a job loaded from a registered Compose project has its compose files: they are in Project.Files, not in File, which the configuration validator checks (config.RequirementSatisfier).

func (*ComposeJob) SchedulePolicy added in v1.1.0

func (j *ComposeJob) SchedulePolicy() (SchedulePolicy, bool)

SchedulePolicy reports the durable schedule policy of a job loaded from a registered Compose project whose schedule sets missed_fires: one or concurrency: queue (SchedulePolicyProvider, ADR-005).

func (*ComposeJob) Use added in v0.9.0

func (c *ComposeJob) Use(ms ...Middleware)

func (*ComposeJob) WorkloadRunning added in v1.1.0

func (j *ComposeJob) WorkloadRunning(ctx context.Context, executionID string) (bool, error)

WorkloadRunning reports whether the run container of the execution still runs (WorkloadChecker). It finds it by ComposeExecutionLabel, including a run from before the job switched to exec mode. An exec command creates no labeled container of its own and therefore cannot be observed this way.

type ComposeProjectContext added in v1.1.0

type ComposeProjectContext struct {
	Files            []string `hash:"true"`
	Profiles         []string `hash:"true"`
	EnvFiles         []string `hash:"true"`
	ProjectName      string   `hash:"true"`
	ProjectDirectory string   `hash:"true"`
	// Revision identifies the job's definition in the loaded configuration;
	// each execution logs it.
	Revision string `hash:"true"`
	// TimeZone describes the zone the schedule is evaluated in, as resolved at
	// load, for logs. It is not hashed: for the local zone it carries the
	// current abbreviation and offset, which change at every daylight-saving
	// switch, and an explicit zone is already part of the schedule (CRON_TZ).
	TimeZone string
	// MissedFires and Concurrency are the schedule's policies from the
	// Compose file ("one" or "skip", "forbid" or "queue"). With "one" or
	// "queue" the job keeps a schedule record (ADR-005).
	MissedFires string `hash:"true"`
	Concurrency string `hash:"true"`
	// Snapshot holds the accepted, resolved model for an imported job. The
	// definition revision covers its relevant inputs; the whole snapshot is
	// deliberately excluded from the hash so unrelated jobs stay unchanged.
	Snapshot *ComposeExecutionSnapshot `json:"-"`
}

ComposeProjectContext is the project selection a job loaded from a registered Compose project runs with. When Files is set it replaces File, and Service names the Compose job. Every field except TimeZone takes part in the job hash, so a changed project replaces the job on reload.

type ContainerInspector added in v0.23.0

type ContainerInspector interface {
	InspectContainer(ctx context.Context, containerID string) (*domain.Container, error)
}

ContainerInspector is a narrow interface for inspecting containers. Satisfied by DockerProvider.

type ContainerLogsOptions added in v0.12.0

type ContainerLogsOptions struct {
	ShowStdout bool
	ShowStderr bool
	Since      time.Time
	Tail       string
	Follow     bool
}

ContainerLogsOptions defines options for container log retrieval.

type Context

type Context struct {
	Scheduler *Scheduler
	Logger    *slog.Logger
	Job       Job
	Execution *Execution
	Ctx       context.Context //nolint:containedctx // intentional: propagates go-cron's per-entry context through middleware chain
	// contains filtered or unexported fields
}

Context carries everything a single job invocation needs: the owning scheduler, the logger, the job, its Execution record, and the per-run context.Context used for outbound calls (reach for it via RunContext, which supplies a fallback when Ctx is unset).

It also holds the cursor into the middleware chain, which is snapshotted from the job at construction. A Context is therefore single-use — one per invocation, never reused or shared — and not safe for concurrent use. Construct it with NewContextWithContext, or NewContext when no parent context is available.

func NewContext

func NewContext(s *Scheduler, j Job, e *Execution) *Context

NewContext constructs a Context with a non-nil default Ctx (context.TODO()). Prefer NewContextWithContext to thread the scheduler's per-run, deadline-bounded context through the middleware chain; NewContext is kept for legacy callers that have no parent context yet.

The default is context.TODO (not context.Background) to flag — both to readers and to static analyzers — that the caller still owes a real parent context. See issue #638.

func NewContextWithContext added in v0.20.0

func NewContextWithContext(ctx context.Context, s *Scheduler, j Job, e *Execution) *Context

NewContextWithContext creates a Context with a specific context.Context, typically the per-entry, deadline-bounded context produced by the scheduler around each invocation. The provided ctx must be non-nil; a nil ctx is replaced with context.TODO() so downstream RunContext() always returns a usable context.

func (*Context) Log

func (c *Context) Log(msg string)

Log writes msg to the logger, prefixed with the job name and execution ID. The level follows the execution's outcome: Error when it failed, Warn when it was skipped, Info otherwise — so the level is only meaningful after Stop has classified the execution.

func (*Context) Next

func (c *Context) Next() error

Next advances the middleware chain by one step, running the next middleware or, once the chain is exhausted, the job itself. Middleware Run implementations must call it, otherwise the chain stalls and the job never executes. Once the execution has stopped, only middlewares whose ContinueOnStop reports true are still run.

Next always returns nil. An error from a middleware or from the job is recorded on the Execution through Stop rather than propagated, so callers read the outcome from Execution.Failed and Execution.Error.

func (*Context) RunContext added in v0.25.0

func (c *Context) RunContext() context.Context

RunContext returns the context.Context that job Run methods should use for outbound calls (Docker SDK, env-from inspections, etc.). It returns c.Ctx when set; otherwise context.Background() so legacy *Context{} literals (e.g. in tests that predate context plumbing) keep working.

Centralizing the fallback here is the foundation for issue #638: it replaces four inline `if runCtx == nil { runCtx = context.Background() }` blocks (execjob, runjob, runservice, localjob) with a single call site.

func (*Context) Start

func (c *Context) Start()

Start marks the execution as running, stamps its start time and increments the job's in-flight counter. Call it once, before entering the middleware chain via Next.

func (*Context) Stop

func (c *Context) Stop(err error)

Stop finalizes the execution with err — nil for success, ErrSkippedExecution to mark it skipped, any other error to mark it failed — records the duration and decrements the job's in-flight counter. Calling it on an execution that has already stopped is a no-op, so both the middleware chain and the caller may invoke it.

func (*Context) Warn

func (c *Context) Warn(msg string)

Warn writes msg at Warn level with the same job-name and execution-ID prefix as Log, regardless of how the execution turned out.

type CronClock added in v0.17.0

type CronClock struct {
	*FakeClock
}

CronClock is a FakeClock that also satisfies the clock interface of github.com/netresearch/go-cron, which requires NewTimer to return a cron.Timer. Pass it to cron.WithClock (see NewSchedulerWithClock) to step a scheduler's cron engine through time from a test.

func NewCronClock added in v0.17.0

func NewCronClock(start time.Time) *CronClock

NewCronClock returns a CronClock over a fresh FakeClock starting at start.

func (*CronClock) NewTimer added in v0.17.0

func (c *CronClock) NewTimer(d time.Duration) cron.Timer

NewTimer shadows FakeClock.NewTimer to return the embedded timer as a cron.Timer. The timer itself is the same one FakeClock hands out.

type CronUtils

type CronUtils struct {
	Logger *slog.Logger
}

CronUtils adapts an slog.Logger to the logger interface expected by github.com/netresearch/go-cron.

func NewCronUtils

func NewCronUtils(l *slog.Logger) *CronUtils

NewCronUtils returns a CronUtils that forwards the cron engine's output to l.

func (*CronUtils) Error

func (c *CronUtils) Error(err error, msg string, keysAndValues ...any)

func (*CronUtils) Info

func (c *CronUtils) Info(msg string, keysAndValues ...any)

Info records an informational cron engine message. It logs at debug level, keeping the engine's per-tick scheduling chatter out of ofelia's info output.

type DependencyProvider added in v0.21.2

type DependencyProvider interface {
	GetDependencies() []string
	GetOnSuccess() []string
	GetOnFailure() []string
	GetName() string
}

DependencyProvider is implemented by jobs that can declare workflow dependencies. BareJob implements this interface, and since ExecJob, RunJob, LocalJob, etc. embed BareJob, they automatically satisfy it via promoted methods.

type DockerProvider added in v0.12.0

type DockerProvider interface {
	// Container operations
	CreateContainer(ctx context.Context, config *domain.ContainerConfig, name string) (string, error)
	StartContainer(ctx context.Context, containerID string) error
	StopContainer(ctx context.Context, containerID string, opts domain.StopOptions) error
	RemoveContainer(ctx context.Context, containerID string, force bool) error
	InspectContainer(ctx context.Context, containerID string) (*domain.Container, error)
	ListContainers(ctx context.Context, opts domain.ListOptions) ([]domain.Container, error)
	WaitContainer(ctx context.Context, containerID string) (int64, error)
	GetContainerLogs(ctx context.Context, containerID string, opts ContainerLogsOptions) (io.ReadCloser, error)
	// CopyContainerLogs streams container logs into stdout/stderr,
	// demultiplexing Docker's 8-byte-framed stream for non-TTY
	// containers (TTY containers emit a raw stream and are copied
	// verbatim). Use this instead of GetContainerLogs whenever the
	// output is stored or displayed — the raw reader leaks frame
	// headers into the log text.
	CopyContainerLogs(ctx context.Context, containerID string, stdout, stderr io.Writer, opts ContainerLogsOptions) error

	// Exec operations
	CreateExec(ctx context.Context, containerID string, config *domain.ExecConfig) (string, error)
	StartExec(ctx context.Context, execID string, opts domain.ExecStartOptions) (*domain.HijackedResponse, error)
	InspectExec(ctx context.Context, execID string) (*domain.ExecInspect, error)
	RunExec(ctx context.Context, containerID string, config *domain.ExecConfig, stdout, stderr io.Writer) (int, error)

	// Image operations
	PullImage(ctx context.Context, image string) error
	HasImageLocally(ctx context.Context, image string) (bool, error)
	EnsureImage(ctx context.Context, image string, forcePull bool) error

	// Network operations
	ConnectNetwork(ctx context.Context, networkID, containerID string) error
	FindNetworkByName(ctx context.Context, networkName string) ([]domain.Network, error)

	// Event operations
	SubscribeEvents(ctx context.Context, filter domain.EventFilter) (<-chan domain.Event, <-chan error)

	// Service operations (Swarm)
	CreateService(ctx context.Context, spec domain.ServiceSpec, opts domain.ServiceCreateOptions) (string, error)
	InspectService(ctx context.Context, serviceID string) (*domain.Service, error)
	ListTasks(ctx context.Context, opts domain.TaskListOptions) ([]domain.Task, error)
	RemoveService(ctx context.Context, serviceID string) error
	WaitForServiceTasks(ctx context.Context, serviceID string, timeout time.Duration) ([]domain.Task, error)

	// System operations
	Info(ctx context.Context) (*domain.SystemInfo, error)
	Ping(ctx context.Context) error

	// Lifecycle
	Close() error
}

DockerProvider defines the interface for Docker operations. The SDK adapter implements this interface.

type EnhancedBufferPool added in v0.11.0

type EnhancedBufferPool struct {
	// contains filtered or unexported fields
}

EnhancedBufferPool provides high-performance buffer management with adaptive sizing

func NewBufferPool added in v0.10.1

func NewBufferPool(minSize, defaultSize, maxSize int64) *EnhancedBufferPool

NewBufferPool is a compatibility wrapper for tests and old code It returns the enhanced buffer pool with custom configuration

func NewEnhancedBufferPool added in v0.11.0

func NewEnhancedBufferPool(config *EnhancedBufferPoolConfig, logger *slog.Logger) *EnhancedBufferPool

NewEnhancedBufferPool creates a new enhanced buffer pool with adaptive management

func (*EnhancedBufferPool) Get added in v0.11.0

func (ebp *EnhancedBufferPool) Get() (*circbuf.Buffer, error)

Get retrieves a buffer from the pool, optimized for high concurrency

func (*EnhancedBufferPool) GetSized added in v0.11.0

func (ebp *EnhancedBufferPool) GetSized(requestedSize int64) (*circbuf.Buffer, error)

GetSized retrieves a buffer with a specific size requirement, with intelligent size selection

func (*EnhancedBufferPool) GetStats added in v0.11.0

func (ebp *EnhancedBufferPool) GetStats() map[string]any

GetStats returns comprehensive performance statistics

func (*EnhancedBufferPool) Put added in v0.11.0

func (ebp *EnhancedBufferPool) Put(buf *circbuf.Buffer)

Put returns a buffer to the appropriate pool

func (*EnhancedBufferPool) Shutdown added in v0.11.0

func (ebp *EnhancedBufferPool) Shutdown()

Shutdown gracefully stops the enhanced buffer pool

type EnhancedBufferPoolConfig added in v0.11.0

type EnhancedBufferPoolConfig struct {
	MinSize          int64         `json:"minSize"`          // Minimum buffer size
	DefaultSize      int64         `json:"defaultSize"`      // Default buffer size
	MaxSize          int64         `json:"maxSize"`          // Maximum buffer size
	PoolSize         int           `json:"poolSize"`         // Number of buffers to pre-allocate
	MaxPoolSize      int           `json:"maxPoolSize"`      // Maximum number of buffers in pool
	GrowthFactor     float64       `json:"growthFactor"`     // Factor to increase pool size when needed
	ShrinkThreshold  float64       `json:"shrinkThreshold"`  // Usage percentage below which to shrink
	ShrinkInterval   time.Duration `json:"shrinkInterval"`   // How often to check for shrinking
	EnableMetrics    bool          `json:"enableMetrics"`    // Enable performance metrics
	EnablePrewarming bool          `json:"enablePrewarming"` // Pre-allocate buffers on startup
}

EnhancedBufferPoolConfig holds configuration for the enhanced buffer pool

func DefaultEnhancedBufferPoolConfig added in v0.11.0

func DefaultEnhancedBufferPoolConfig() *EnhancedBufferPoolConfig

DefaultEnhancedBufferPoolConfig returns optimized defaults for high-concurrency scenarios

type ExecJob

type ExecJob struct {
	BareJob   `mapstructure:",squash"`
	Provider  DockerProvider `json:"-"` // SDK-based Docker provider
	Container string         `hash:"true"`
	// User specifies the user to run the command as.
	// If not set, uses the global default-user setting (default: "nobody").
	// Set to "default" to explicitly use the container's default user, overriding global setting.
	User        string   `hash:"true"`
	TTY         bool     `default:"false" hash:"true"`
	Environment []string `mapstructure:"environment" hash:"true"`
	EnvFile     []string `gcfg:"env-file" mapstructure:"env-file," hash:"true"`
	EnvFrom     []string `gcfg:"env-from" mapstructure:"env-from," hash:"true"`
	WorkingDir  string   `mapstructure:"working-dir" hash:"true"`
	Privileged  bool     `default:"false" hash:"true"`

	// ConsoleHeight / ConsoleWidth set the initial pseudo-TTY console
	// size (rows × columns) sent to the Docker daemon at exec creation
	// — useful for jobs that render TUIs / tables and need a consistent
	// terminal geometry. Both default to 0, meaning "use Docker's
	// default size"; setting either populates the daemon's ConsoleSize
	// parameter. Only honored when TTY is true; otherwise silently
	// ignored by the daemon. Requires Docker API v1.42+ (Docker Engine
	// 20.10+, released 2020-12).
	// See https://github.com/netresearch/ofelia/issues/235.
	ConsoleHeight uint `gcfg:"console-height" mapstructure:"console-height" hash:"true"`
	ConsoleWidth  uint `gcfg:"console-width" mapstructure:"console-width" hash:"true"`
}

ExecJob runs a command inside an already-running container via `docker exec`. The container named by Container must exist and be running; Ofelia neither creates nor removes it, so state left behind by the command persists in that container. See Run for the cancellation limitation.

func NewExecJob

func NewExecJob(provider DockerProvider) *ExecJob

NewExecJob returns an ExecJob bound to provider, which is the Docker connection the exec session is created on. Container, the embedded BareJob and the remaining options are set by the caller.

func (*ExecJob) Hash added in v0.9.0

func (j *ExecJob) Hash() (string, error)

Hash returns the change-detection key over every `hash:"true"` field of the exec job, the embedded BareJob fields included.

func (*ExecJob) InitializeRuntimeFields added in v0.10.2

func (j *ExecJob) InitializeRuntimeFields()

InitializeRuntimeFields initializes fields that depend on the Docker provider. This should be called after the Provider field is set.

func (*ExecJob) Middlewares

func (c *ExecJob) Middlewares() []Middleware

func (*ExecJob) ResetMiddlewares added in v0.9.0

func (c *ExecJob) ResetMiddlewares(ms ...Middleware)

func (*ExecJob) Run

func (j *ExecJob) Run(ctx *Context) error

Run executes the configured command inside the target container via `docker exec`.

Limitation (issue #655): when the wrapper-level deadline from #651's boundJobContext fires (or any other ctx cancellation occurs), Ofelia stops reading the output but the in-container process is left running. The Docker Engine API exposes no `ExecStop` primitive — once an exec session is started Ofelia cannot kill the inner process from the outside. Operators relying on a hard ceiling for `job-exec` MUST enforce it inside the entrypoint (e.g. `timeout 30s ...`) rather than via `max-runtime` alone.

What Ofelia does instead is report what happened. After a cancellation that comes once the exec was created, it inspects the exec on a fresh context: a process that has exited meanwhile is classified by its exit code as usual; one that is still running yields ErrMaxTimeRunning wrapped with ErrExecStillRunning, and a failed inspection yields ErrMaxTimeRunning wrapped with ErrExecOutcomeUnknown. Both name the exec ID, so the execution record never claims that the command stopped. A cancellation before the exec was created yields ErrMaxTimeRunning with the context error; no process was started then.

func (*ExecJob) RunWithStreams added in v0.12.0

func (j *ExecJob) RunWithStreams(ctx context.Context, stdout, stderr io.Writer) (int, error)

RunWithStreams runs the exec job with custom output streams. This is useful for testing or when custom stream handling is needed.

func (*ExecJob) Use

func (c *ExecJob) Use(ms ...Middleware)

type Execution

type Execution struct {
	ID        string
	Date      time.Time
	Duration  time.Duration
	IsRunning bool
	Failed    bool
	Skipped   bool
	Error     error

	OutputStream, ErrorStream *circbuf.Buffer `json:"-"`

	// Captured output for persistence after buffer cleanup
	CapturedStdout, CapturedStderr string `json:"-"`
}

Execution contains all the information relative to a Job execution.

func NewExecution

func NewExecution() (*Execution, error)

NewExecution returns a new Execution, with a random ID

func (*Execution) Cleanup added in v0.10.1

func (e *Execution) Cleanup()

Cleanup returns execution buffers to the pool for reuse

func (*Execution) GetStderr added in v0.10.1

func (e *Execution) GetStderr() string

GetStderr returns stderr content, preferring live buffer if available

func (*Execution) GetStdout added in v0.10.1

func (e *Execution) GetStdout() string

GetStdout returns stdout content, preferring live buffer if available

func (*Execution) Start

func (e *Execution) Start()

Start starts the execution, initializes the running flags and the start date.

func (*Execution) Stop

func (e *Execution) Stop(err error)

Stop halts the execution. If a ErrSkippedExecution is given the execution is marked as skipped; if any other error is given the execution is marked as failed. Also mark the execution as IsRunning false and save the duration time

type FakeClock added in v0.17.0

type FakeClock struct {
	// contains filtered or unexported fields
}

FakeClock is a Clock whose time only moves when Advance or Set is called. Tickers, timers and After channels derived from it fire in chronological order as time is moved forward. All methods are safe for concurrent use.

func NewFakeClock added in v0.17.0

func NewFakeClock(start time.Time) *FakeClock

NewFakeClock returns a FakeClock that reports start until it is advanced.

func (*FakeClock) Advance added in v0.17.0

func (c *FakeClock) Advance(d time.Duration)

Advance moves the clock forward by d, stopping at each ticker, timer and After deadline in the interval so events fire in chronological order.

func (*FakeClock) After added in v0.17.0

func (c *FakeClock) After(d time.Duration) <-chan time.Time

After returns a channel that receives the fake time once d has elapsed on this clock. A non-positive d delivers the current time immediately.

func (*FakeClock) NewTicker added in v0.17.0

func (c *FakeClock) NewTicker(d time.Duration) Ticker

NewTicker returns a Ticker that fires every d of fake time. Its channel holds a single tick; ticks produced while that buffer is full are dropped, as with time.Ticker. The ticker is tracked by the clock until it is stopped.

func (*FakeClock) NewTimer added in v0.17.0

func (c *FakeClock) NewTimer(d time.Duration) Timer

NewTimer returns a Timer that fires once, d of fake time from now. Resetting it schedules the next firing relative to the clock's time at that moment.

func (*FakeClock) Now added in v0.17.0

func (c *FakeClock) Now() time.Time

Now returns the clock's current fake time.

func (*FakeClock) Set added in v0.17.0

func (c *FakeClock) Set(t time.Time)

Set moves the clock to t, firing the events in between as Advance does. Setting a time in the past fires nothing and only changes what Now reports.

func (*FakeClock) Sleep added in v0.17.0

func (c *FakeClock) Sleep(d time.Duration)

Sleep blocks until the clock has moved d forward, returning at once for a non-positive d. Only Advance or Set unblocks it, so the code advancing the clock must run in another goroutine.

func (*FakeClock) TickerCount added in v0.17.0

func (c *FakeClock) TickerCount() int

TickerCount returns how many tickers created from this clock have not been stopped, letting tests assert that scheduling code cleans up after itself.

func (*FakeClock) WaitForAdvance added in v0.17.0

func (c *FakeClock) WaitForAdvance()

WaitForAdvance blocks until an Advance or Set has completed. Completions are buffered, so a call may return immediately for an earlier advance.

type GracefulScheduler added in v0.10.1

type GracefulScheduler struct {
	*Scheduler
	// contains filtered or unexported fields
}

GracefulScheduler wraps a scheduler with graceful shutdown

func NewGracefulScheduler added in v0.10.1

func NewGracefulScheduler(scheduler *Scheduler, shutdownManager *ShutdownManager) *GracefulScheduler

NewGracefulScheduler creates a scheduler with graceful shutdown support

func (GracefulScheduler) Middlewares added in v0.10.1

func (c GracefulScheduler) Middlewares() []Middleware

func (GracefulScheduler) ResetMiddlewares added in v0.10.1

func (c GracefulScheduler) ResetMiddlewares(ms ...Middleware)

func (*GracefulScheduler) RunJobWithTracking added in v0.10.1

func (gs *GracefulScheduler) RunJobWithTracking(job Job, ctx *Context) error

RunJobWithTracking runs a job with shutdown tracking

func (GracefulScheduler) Use added in v0.10.1

func (c GracefulScheduler) Use(ms ...Middleware)

type GracefulServer added in v0.10.1

type GracefulServer struct {
	// contains filtered or unexported fields
}

GracefulServer wraps an HTTP server with graceful shutdown

func NewGracefulServer added in v0.10.1

func NewGracefulServer(server *http.Server, shutdownManager *ShutdownManager, logger *slog.Logger) *GracefulServer

NewGracefulServer creates a server with graceful shutdown support

type Job

type Job interface {
	GetName() string
	GetSchedule() string
	GetCommand() string
	ShouldRunOnStartup() bool
	Middlewares() []Middleware
	Use(...Middleware)
	Run(*Context) error
	Running() int32
	NotifyStart()
	NotifyStop()
	GetCronJobID() uint64
	SetCronJobID(uint64)
	GetHistory() []*Execution
	Hash() (string, error)
}

Job is the contract the scheduler requires of anything it can run. Embedding BareJob provides every method here except Run through promoted methods, so a job type normally implements Run only.

GetName, GetSchedule and ShouldRunOnStartup are read at registration time; Middlewares and Use manage the per-job middleware chain; Running, NotifyStart and NotifyStop track in-flight invocations; GetCronJobID and SetCronJobID carry the go-cron entry ID; Hash reports a change-detection key over the job's configuration.

type JobMetrics added in v0.11.0

type JobMetrics struct {
	ExecutionCount  int64
	TotalDuration   time.Duration
	AverageDuration time.Duration
	MinDuration     time.Duration
	MaxDuration     time.Duration
	SuccessCount    int64
	FailureCount    int64
	LastExecution   time.Time
	LastSuccess     time.Time
	LastFailure     time.Time
}

JobMetrics holds metrics for individual jobs

type JobMetricsRecorder added in v0.10.1

type JobMetricsRecorder interface {
	RecordMetric(name string, value any)
	RecordJobExecution(jobName string, success bool, duration time.Duration)
	RecordRetryAttempt(jobName string, attempt int, success bool)
}

JobMetricsRecorder interface for recording job-specific metrics

type LatencyTracker added in v0.11.0

type LatencyTracker struct {
	Count   int64
	Total   time.Duration
	Min     time.Duration
	Max     time.Duration
	Average time.Duration
	// contains filtered or unexported fields
}

LatencyTracker tracks latency statistics for operations

type LocalJob

type LocalJob struct {
	BareJob     `mapstructure:",squash"`
	Dir         string   `hash:"true"`
	Environment []string `mapstructure:"environment" hash:"true"`
	EnvFile     []string `gcfg:"env-file" mapstructure:"env-file," hash:"true"`
	EnvFrom     []string `gcfg:"env-from" mapstructure:"env-from," hash:"true"`
}

LocalJob runs a command directly on the host Ofelia runs on, outside any container. The child inherits Ofelia's own environment, extended by EnvFile and Environment; EnvFrom is accepted but inert on this path because no Docker provider is passed to the resolver (see localJobEnvResolveTimeout).

func NewLocalJob

func NewLocalJob() *LocalJob

NewLocalJob returns an empty LocalJob; the caller fills in the embedded BareJob, Dir and the environment fields.

func (*LocalJob) Hash added in v0.9.0

func (j *LocalJob) Hash() (string, error)

Hash returns the change-detection key over every `hash:"true"` field of the local job, the embedded BareJob fields included.

func (*LocalJob) Middlewares

func (c *LocalJob) Middlewares() []Middleware

func (*LocalJob) ResetMiddlewares added in v0.9.0

func (c *LocalJob) ResetMiddlewares(ms ...Middleware)

func (*LocalJob) Run

func (j *LocalJob) Run(ctx *Context) error

Run looks up the binary on PATH, resolves the environment and executes the command in Dir, blocking until the process exits. Returns ErrEmptyCommand for an empty command, a lookup error when the binary is not on PATH, the env-resolution error, or the process's exit error. Output is streamed to the execution's stdout/stderr streams.

The process is bound to the run context. When the run is canceled — on scheduler shutdown, job removal or the execution time limit — Run sends SIGTERM to the process group the command runs in, sends SIGKILL to whatever is left after localJobStopGrace, and returns ErrMaxTimeRunning. On Windows, which has no process groups or SIGTERM, only the command's own process is killed, at once.

func (*LocalJob) Use

func (c *LocalJob) Use(ms ...Middleware)

type MaxRuntimeProvider added in v0.25.0

type MaxRuntimeProvider interface {
	// GetMaxRuntime returns the job's own max-runtime; 0 means none.
	GetMaxRuntime() time.Duration
	// InheritsGlobalMaxRuntime reports whether a job without a max-runtime
	// of its own runs under the scheduler's `[global] max-runtime`
	// (SetGlobalMaxRuntime). A compose job in exec mode does not.
	InheritsGlobalMaxRuntime() bool
}

MaxRuntimeProvider is implemented by job types that expose a per-job maximum runtime. Currently RunJob, RunServiceJob and ComposeJob satisfy this interface; ExecJob and LocalJob do not, and run under defaultJobMaxRuntime.

type MetricsRecorder added in v0.10.1

type MetricsRecorder interface {
	RecordJobRetry(jobName string, attempt int, success bool)
	RecordContainerEvent()
	RecordContainerMonitorFallback()
	RecordContainerMonitorMethod(usingEvents bool)
	RecordContainerWaitDuration(seconds float64)
	RecordDockerOperation(operation string)
	RecordDockerError(operation string)
	// Job scheduling metrics (from go-cron ObservabilityHooks)
	RecordJobStart(jobName string)
	RecordJobComplete(jobName string, durationSeconds float64, panicked bool)
	RecordJobScheduled(jobName string)
	// Workflow completion metrics (from go-cron ObservabilityHooks)
	RecordWorkflowComplete(rootJobName, status string)
	RecordWorkflowJobResult(jobName, result string)
}

MetricsRecorder interface for recording retry and monitoring metrics

type Middleware

type Middleware interface {
	// Run is called instead of the original `Job.Run`, you MUST call to `ctx.Run`
	// inside of the middleware `Run` function otherwise you will broken the
	// Job workflow.
	Run(*Context) error
	// ContinueOnStop reports whether Run should be called even when the
	// execution has been stopped
	ContinueOnStop() bool
}

Middleware can wrap any job execution, allowing to execution code before or/and after of each `Job.Run`

type NonZeroExitError added in v0.10.1

type NonZeroExitError struct {
	ExitCode int
}

NonZeroExitError represents a container exit with non-zero code

func (NonZeroExitError) Error added in v0.10.1

func (e NonZeroExitError) Error() string

type PerformanceMetrics added in v0.11.0

type PerformanceMetrics struct {
	// contains filtered or unexported fields
}

PerformanceMetrics implements comprehensive performance tracking

func NewPerformanceMetrics added in v0.11.0

func NewPerformanceMetrics() *PerformanceMetrics

NewPerformanceMetrics creates a new performance metrics recorder

func (*PerformanceMetrics) GetDockerMetrics added in v0.11.0

func (pm *PerformanceMetrics) GetDockerMetrics() map[string]any

GetDockerMetrics returns Docker-specific metrics

func (*PerformanceMetrics) GetJobMetrics added in v0.11.0

func (pm *PerformanceMetrics) GetJobMetrics() map[string]any

GetJobMetrics returns job execution metrics

func (*PerformanceMetrics) GetMetrics added in v0.11.0

func (pm *PerformanceMetrics) GetMetrics() map[string]any

GetMetrics returns all performance metrics

func (*PerformanceMetrics) GetSummaryReport added in v0.11.0

func (pm *PerformanceMetrics) GetSummaryReport() string

GetSummaryReport generates a human-readable performance summary

func (*PerformanceMetrics) RecordBufferPoolStats added in v0.11.0

func (pm *PerformanceMetrics) RecordBufferPoolStats(stats map[string]any)

RecordBufferPoolStats records buffer pool performance statistics

func (*PerformanceMetrics) RecordConcurrentJobs added in v0.11.0

func (pm *PerformanceMetrics) RecordConcurrentJobs(count int64)

RecordConcurrentJobs tracks the number of concurrent jobs

func (*PerformanceMetrics) RecordContainerEvent added in v0.11.0

func (pm *PerformanceMetrics) RecordContainerEvent()

RecordContainerEvent records container events

func (*PerformanceMetrics) RecordContainerMonitorFallback added in v0.11.0

func (pm *PerformanceMetrics) RecordContainerMonitorFallback()

RecordContainerMonitorFallback records container monitor fallbacks

func (*PerformanceMetrics) RecordContainerMonitorMethod added in v0.11.0

func (pm *PerformanceMetrics) RecordContainerMonitorMethod(usingEvents bool)

RecordContainerMonitorMethod records container monitor method usage

func (*PerformanceMetrics) RecordContainerWaitDuration added in v0.11.0

func (pm *PerformanceMetrics) RecordContainerWaitDuration(seconds float64)

RecordContainerWaitDuration records container wait durations

func (*PerformanceMetrics) RecordCustomMetric added in v0.11.0

func (pm *PerformanceMetrics) RecordCustomMetric(name string, value any)

RecordCustomMetric records a custom metric

func (*PerformanceMetrics) RecordDockerError added in v0.11.0

func (pm *PerformanceMetrics) RecordDockerError(operation string)

RecordDockerError records a Docker operation error

func (*PerformanceMetrics) RecordDockerLatency added in v0.11.0

func (pm *PerformanceMetrics) RecordDockerLatency(operation string, duration time.Duration)

RecordDockerLatency records the latency of a Docker operation

func (*PerformanceMetrics) RecordDockerOperation added in v0.11.0

func (pm *PerformanceMetrics) RecordDockerOperation(operation string)

RecordDockerOperation records a successful Docker operation

func (*PerformanceMetrics) RecordJobComplete added in v0.13.0

func (pm *PerformanceMetrics) RecordJobComplete(jobName string, durationSeconds float64, panicked bool)

RecordJobComplete records a job completing (from go-cron ObservabilityHooks)

func (*PerformanceMetrics) RecordJobExecution added in v0.11.0

func (pm *PerformanceMetrics) RecordJobExecution(jobName string, duration time.Duration, success bool)

RecordJobExecution records a job execution with timing and success status

func (*PerformanceMetrics) RecordJobRetry added in v0.11.0

func (pm *PerformanceMetrics) RecordJobRetry(jobName string, attempt int, success bool)

RecordJobRetry records job retry attempts

func (*PerformanceMetrics) RecordJobScheduled added in v0.11.0

func (pm *PerformanceMetrics) RecordJobScheduled(jobName string)

RecordJobScheduled records when a job is scheduled

func (*PerformanceMetrics) RecordJobSkipped added in v0.11.0

func (pm *PerformanceMetrics) RecordJobSkipped(jobName, reason string)

RecordJobSkipped records when a job is skipped

func (*PerformanceMetrics) RecordJobStart added in v0.13.0

func (pm *PerformanceMetrics) RecordJobStart(jobName string)

RecordJobStart records a job start (from go-cron ObservabilityHooks)

func (*PerformanceMetrics) RecordMemoryUsage added in v0.11.0

func (pm *PerformanceMetrics) RecordMemoryUsage(bytes int64)

RecordMemoryUsage tracks memory usage

func (*PerformanceMetrics) RecordWorkflowComplete added in v0.21.0

func (pm *PerformanceMetrics) RecordWorkflowComplete(rootJobName, status string)

RecordWorkflowComplete records a workflow completion event. No-op: workflow metrics are tracked via the Prometheus Collector, not PerformanceMetrics.

func (*PerformanceMetrics) RecordWorkflowJobResult added in v0.21.0

func (pm *PerformanceMetrics) RecordWorkflowJobResult(jobName, result string)

RecordWorkflowJobResult records an individual job result within a workflow. No-op: workflow metrics are tracked via the Prometheus Collector, not PerformanceMetrics.

func (*PerformanceMetrics) Reset added in v0.11.0

func (pm *PerformanceMetrics) Reset()

Reset clears all metrics (useful for testing or periodic resets)

type PerformanceRecorder added in v0.11.0

type PerformanceRecorder interface {
	MetricsRecorder // Embed existing interface (includes RecordDockerError and job scheduling metrics)

	// Extended Docker operations
	RecordDockerLatency(operation string, duration time.Duration)

	// Job operations (extended beyond MetricsRecorder)
	RecordJobExecution(jobName string, duration time.Duration, success bool)
	RecordJobSkipped(jobName, reason string)

	// System metrics
	RecordConcurrentJobs(count int64)
	RecordMemoryUsage(bytes int64)
	RecordBufferPoolStats(stats map[string]any)

	// Custom metrics
	RecordCustomMetric(name string, value any)

	// Retrieval
	GetMetrics() map[string]any
	GetDockerMetrics() map[string]any
	GetJobMetrics() map[string]any
	Reset()
}

PerformanceRecorder defines the interface for recording comprehensive performance metrics This extends the existing MetricsRecorder interface with additional capabilities

type RateLimiter added in v0.10.1

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter implements token bucket rate limiting

func NewRateLimiter added in v0.10.1

func NewRateLimiter(rate float64, capacity int) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow added in v0.10.1

func (rl *RateLimiter) Allow() bool

Allow checks if a request is allowed

func (*RateLimiter) AllowN added in v0.10.1

func (rl *RateLimiter) AllowN(n int) bool

AllowN checks if n requests are allowed

func (*RateLimiter) Wait added in v0.10.1

func (rl *RateLimiter) Wait(ctx context.Context) error

Wait blocks until a request is allowed

func (*RateLimiter) WaitN added in v0.10.1

func (rl *RateLimiter) WaitN(ctx context.Context, n int) error

WaitN blocks until n requests are allowed

type ResilientJobExecutor added in v0.10.1

type ResilientJobExecutor struct {
	// contains filtered or unexported fields
}

ResilientJobExecutor wraps job execution with resilience patterns

func NewResilientJobExecutor added in v0.10.1

func NewResilientJobExecutor(job Job) *ResilientJobExecutor

NewResilientJobExecutor creates a new resilient job executor

func (*ResilientJobExecutor) Execute added in v0.10.1

func (rje *ResilientJobExecutor) Execute(ctx *Context) error

Execute runs the job with resilience patterns

func (*ResilientJobExecutor) GetCircuitBreakerState added in v0.10.1

func (rje *ResilientJobExecutor) GetCircuitBreakerState() CircuitBreakerState

GetCircuitBreakerState returns the current state of the circuit breaker

func (*ResilientJobExecutor) ResetCircuitBreaker added in v0.10.1

func (rje *ResilientJobExecutor) ResetCircuitBreaker()

ResetCircuitBreaker manually resets the circuit breaker

func (*ResilientJobExecutor) SetBulkhead added in v0.10.1

func (rje *ResilientJobExecutor) SetBulkhead(bh *Bulkhead)

SetBulkhead updates the bulkhead

func (*ResilientJobExecutor) SetCircuitBreaker added in v0.10.1

func (rje *ResilientJobExecutor) SetCircuitBreaker(cb *CircuitBreaker)

SetCircuitBreaker updates the circuit breaker

func (*ResilientJobExecutor) SetMetricsRecorder added in v0.10.1

func (rje *ResilientJobExecutor) SetMetricsRecorder(metrics JobMetricsRecorder)

SetMetricsRecorder sets the metrics recorder

func (*ResilientJobExecutor) SetRateLimiter added in v0.10.1

func (rje *ResilientJobExecutor) SetRateLimiter(rl *RateLimiter)

SetRateLimiter updates the rate limiter

func (*ResilientJobExecutor) SetRetryPolicy added in v0.10.1

func (rje *ResilientJobExecutor) SetRetryPolicy(policy *RetryPolicy)

SetRetryPolicy updates the retry policy

type RetryConfig added in v0.10.1

type RetryConfig struct {
	MaxRetries       int
	RetryDelayMs     int
	RetryExponential bool
	RetryMaxDelayMs  int
}

RetryConfig contains retry configuration for a job

type RetryExecutor added in v0.10.1

type RetryExecutor struct {
	// contains filtered or unexported fields
}

RetryExecutor wraps job execution with retry logic

func NewRetryExecutor added in v0.10.1

func NewRetryExecutor(logger *slog.Logger) *RetryExecutor

NewRetryExecutor creates a new retry executor

func (*RetryExecutor) ExecuteWithRetry added in v0.10.1

func (re *RetryExecutor) ExecuteWithRetry(job Job, ctx *Context, runFunc func(*Context) error) error

ExecuteWithRetry executes a job with retry logic

func (*RetryExecutor) SetMetricsRecorder added in v0.10.1

func (re *RetryExecutor) SetMetricsRecorder(metrics MetricsRecorder)

SetMetricsRecorder sets the metrics recorder for the retry executor

type RetryMetrics added in v0.11.0

type RetryMetrics struct {
	TotalAttempts     int64
	SuccessfulRetries int64
	FailedRetries     int64
	LastRetry         time.Time
}

RetryMetrics holds retry-specific metrics

type RetryPolicy added in v0.10.1

type RetryPolicy struct {
	MaxAttempts     int
	InitialDelay    time.Duration
	MaxDelay        time.Duration
	BackoffFactor   float64
	JitterFactor    float64
	RetryableErrors func(error) bool
}

RetryPolicy defines retry behavior

func DefaultRetryPolicy added in v0.10.1

func DefaultRetryPolicy() *RetryPolicy

DefaultRetryPolicy returns a default retry policy

type RetryStats added in v0.10.1

type RetryStats struct {
	JobName       string
	TotalAttempts int
	SuccessAfter  int // Number of retries before success (0 if first attempt succeeded)
	Failed        bool
	LastError     error
}

RetryStats tracks retry statistics for a job

type RetryableJob added in v0.10.1

type RetryableJob interface {
	Job
	GetRetryConfig() RetryConfig
}

RetryableJob interface for jobs that support retries

type RunJob

type RunJob struct {
	BareJob  `mapstructure:",squash"`
	Provider DockerProvider `json:"-"` // SDK-based Docker provider
	// User specifies the user to run the container as.
	// If not set, uses the global default-user setting (default: "nobody").
	// Set to "default" to explicitly use the container's default user, overriding global setting.
	User string `hash:"true"`

	// ContainerName specifies the name of the container to be created. If
	// nil, the job name will be used. If set to an empty string, Docker
	// will assign a random name.
	ContainerName *string `gcfg:"container-name" mapstructure:"container-name" hash:"true"`

	TTY bool `default:"false" hash:"true"`

	// do not use bool values with "default:true" because if
	// user would set it to "false" explicitly, it still will be
	// changed to "true" https://github.com/netresearch/ofelia/issues/135
	// so lets use strings here as workaround
	Delete string `default:"true" hash:"true"`
	Pull   string `default:"true" hash:"true"`

	Image       string   `hash:"true"`
	Network     string   `hash:"true"`
	Hostname    string   `hash:"true"`
	Entrypoint  *string  `hash:"true"`
	Container   string   `hash:"true"`
	Volume      []string `hash:"true"`
	VolumesFrom []string `gcfg:"volumes-from" mapstructure:"volumes-from," hash:"true"`
	Environment []string `mapstructure:"environment" hash:"true"`
	EnvFile     []string `gcfg:"env-file" mapstructure:"env-file," hash:"true"`
	EnvFrom     []string `gcfg:"env-from" mapstructure:"env-from," hash:"true"`
	WorkingDir  string   `gcfg:"working-dir" mapstructure:"working-dir" hash:"true"`
	Annotations []string `mapstructure:"annotations" hash:"true"`

	// StopSignal is the signal sent to the main process when Ofelia
	// stops the container after execution. Accepts the canonical name
	// ("SIGINT") or the bare suffix ("INT"); empty defaults to whatever
	// the container image declared via STOPSIGNAL (which itself falls
	// back to SIGTERM). Useful for apps with signal handlers — Node.js
	// (SIGINT), Java thread-dump-on-quit (SIGQUIT), or custom cleanup
	// handlers (SIGUSR1/SIGUSR2). Requires Docker API v1.42+ (Docker
	// Engine 20.10+, released 2020-12). See
	// https://github.com/netresearch/ofelia/issues/234.
	StopSignal string `gcfg:"stop-signal" mapstructure:"stop-signal" hash:"true"`

	// StopTimeout is the grace period between the stop signal (see
	// StopSignal) and the daemon's escalation to SIGKILL. Honored only
	// by Ofelia's deadline-cleanup path today (cleanupOnDeadline);
	// other shutdown paths inherit the daemon's default (typically 10s,
	// matching the legacy hardcoded value this field replaces).
	// Zero leaves the previous 10s default in effect, so unconfigured
	// jobs see no behavior change. Pair with StopSignal to give apps
	// enough time to flush state before SIGKILL — Node.js graceful
	// shutdown often needs >10s, Java thread-dump on SIGQUIT can take
	// 5-30s depending on heap size. See #234.
	StopTimeout time.Duration `gcfg:"stop-timeout" mapstructure:"stop-timeout" hash:"true"`

	MaxRuntime time.Duration `gcfg:"max-runtime" mapstructure:"max-runtime" hash:"true"`
	// contains filtered or unexported fields
}

RunJob runs a command in a container of its own: it ensures Image is present, creates a container per run, starts it, waits for it to exit and then removes it unless Delete is "false". Setting Container instead of Image reuses an existing container by name — that one is started but never created or removed by Ofelia. Validate requires one of the two.

func NewRunJob

func NewRunJob(provider DockerProvider) *RunJob

NewRunJob returns a RunJob bound to provider, which is the Docker connection the container is created and watched on. The caller sets Image or Container plus the remaining fields; Validate rejects a job with neither.

func (*RunJob) GetMaxRuntime added in v0.25.0

func (j *RunJob) GetMaxRuntime() time.Duration

GetMaxRuntime exposes the configured per-job maximum runtime so the scheduler can wrap the per-run context with a deadline (issue #638). A zero value means "no per-job override"; the run then follows the scheduler's current `[global] max-runtime` (24h without one).

func (*RunJob) InheritsGlobalMaxRuntime added in v1.1.0

func (j *RunJob) InheritsGlobalMaxRuntime() bool

InheritsGlobalMaxRuntime reports that a run job without a max-runtime of its own runs under `[global] max-runtime` (MaxRuntimeProvider).

func (*RunJob) InitializeRuntimeFields added in v0.10.1

func (j *RunJob) InitializeRuntimeFields()

InitializeRuntimeFields initializes fields that depend on the Docker provider. This should be called after the Provider field is set.

func (*RunJob) Middlewares

func (c *RunJob) Middlewares() []Middleware

func (*RunJob) ResetMiddlewares added in v0.9.0

func (c *RunJob) ResetMiddlewares(ms ...Middleware)

func (*RunJob) Run

func (j *RunJob) Run(ctx *Context) error

Run creates or looks up the container, starts it and blocks until it exits, then copies the logs produced since the start of this run to the execution's output stream. It returns nil for exit code 0, ErrUnexpected for -1, NonZeroExitError otherwise, and ErrMaxTimeRunning when MaxRuntime or the run context expires before the container finishes.

A container created by this run is removed before Run returns, unless Delete is "false". If the run context has already expired at that point, teardown switches to a fresh context (jobCleanupTimeout) and stops the container before removing it, so an expired deadline does not leave the container behind — see issue #655.

func (*RunJob) Use

func (c *RunJob) Use(ms ...Middleware)

func (*RunJob) Validate added in v0.16.0

func (j *RunJob) Validate() error

Validate checks that the job configuration is valid. For job-run, either Image or Container must be specified.

type RunServiceJob

type RunServiceJob struct {
	BareJob  `mapstructure:",squash"`
	Provider DockerProvider `json:"-"` // SDK-based Docker provider
	// User specifies the user to run the service as.
	// If not set, uses the global default-user setting (default: "nobody").
	// Set to "default" to explicitly use the container's default user, overriding global setting.
	User string `hash:"true"`
	TTY  bool   `default:"false" hash:"true"`
	// do not use bool values with "default:true" because if
	// user would set it to "false" explicitly, it still will be
	// changed to "true" https://github.com/netresearch/ofelia/issues/135
	// so lets use strings here as workaround
	Delete      string        `default:"true" hash:"true"`
	Image       string        `hash:"true"`
	Network     string        `hash:"true"`
	Hostname    string        `hash:"true"`
	Dir         string        `hash:"true"`
	Volume      []string      `hash:"true"`
	Environment []string      `mapstructure:"environment" hash:"true"`
	EnvFile     []string      `gcfg:"env-file" mapstructure:"env-file," hash:"true"`
	EnvFrom     []string      `gcfg:"env-from" mapstructure:"env-from," hash:"true"`
	Annotations []string      `mapstructure:"annotations" hash:"true"`
	MaxRuntime  time.Duration `gcfg:"max-runtime" mapstructure:"max-runtime" hash:"true"`
}

RunServiceJob runs a command as a one-shot Docker Swarm service: it creates a service whose task has restart condition "none", polls that task until it reaches a terminal state, and removes the service again unless Delete is "false". The provider must be connected to a daemon acting as a Swarm manager. Only the task's exit code is observed — unlike RunJob, no container output is captured into the execution streams.

func NewRunServiceJob

func NewRunServiceJob(provider DockerProvider) *RunServiceJob

NewRunServiceJob returns a RunServiceJob bound to provider, which is the Docker connection the swarm service is created and polled on. The caller sets the remaining fields; Image is mandatory (see Validate).

func (*RunServiceJob) GetMaxRuntime added in v0.25.0

func (j *RunServiceJob) GetMaxRuntime() time.Duration

GetMaxRuntime exposes the configured per-job maximum runtime so the scheduler can wrap the per-run context with a deadline (issue #638). A zero value means "no per-job override"; the run then follows the scheduler's current `[global] max-runtime` (24h without one).

func (*RunServiceJob) Hash added in v0.9.0

func (j *RunServiceJob) Hash() (string, error)

Hash returns the change-detection key over every `hash:"true"` field of the service job, the embedded BareJob fields included.

func (*RunServiceJob) InheritsGlobalMaxRuntime added in v1.1.0

func (j *RunServiceJob) InheritsGlobalMaxRuntime() bool

InheritsGlobalMaxRuntime reports that a service job without a max-runtime of its own runs under `[global] max-runtime` (MaxRuntimeProvider).

func (*RunServiceJob) InitializeRuntimeFields added in v0.12.0

func (j *RunServiceJob) InitializeRuntimeFields()

InitializeRuntimeFields initializes fields that depend on the Docker provider. This should be called after the Provider field is set.

func (*RunServiceJob) Middlewares

func (c *RunServiceJob) Middlewares() []Middleware

func (*RunServiceJob) ResetMiddlewares added in v0.9.0

func (c *RunServiceJob) ResetMiddlewares(ms ...Middleware)

func (*RunServiceJob) Run

func (j *RunServiceJob) Run(ctx *Context) error

Run pulls the image, creates the swarm service and blocks while polling its tasks every 500ms until one reaches a terminal state. It returns nil for task exit code 0, ErrUnexpected for -1 and for ExitCodeSwarmError (no terminal task observed), NonZeroExitError otherwise, and ErrMaxTimeRunning when MaxRuntime elapses first.

The service is removed before Run returns unless Delete is "false"; if the run context has already expired, removal runs on a fresh context (jobCleanupTimeout) so no orphan service is left scheduled — see issue #655. A failed removal is returned as the error only when the run itself succeeded; otherwise the run's own error wins and the removal failure is logged.

func (*RunServiceJob) Use

func (c *RunServiceJob) Use(ms ...Middleware)

func (*RunServiceJob) Validate added in v0.16.0

func (j *RunServiceJob) Validate() error

Validate checks that the job configuration is valid. For job-service-run, Image is required.

type SDKDockerProvider added in v0.12.0

type SDKDockerProvider struct {
	// contains filtered or unexported fields
}

SDKDockerProvider implements DockerProvider using the official Docker SDK.

func NewSDKDockerProvider added in v0.12.0

func NewSDKDockerProvider(cfg *SDKDockerProviderConfig) (*SDKDockerProvider, error)

NewSDKDockerProvider creates a new SDK-based Docker provider.

func NewSDKDockerProviderDefault added in v0.12.0

func NewSDKDockerProviderDefault() (*SDKDockerProvider, error)

NewSDKDockerProviderDefault creates a provider with default settings.

func NewSDKDockerProviderFromClient added in v0.12.0

func NewSDKDockerProviderFromClient(client ports.DockerClient, logger *slog.Logger, metricsRecorder MetricsRecorder) *SDKDockerProvider

NewSDKDockerProviderFromClient creates a provider from an existing client.

func (*SDKDockerProvider) Close added in v0.12.0

func (p *SDKDockerProvider) Close() error

Close closes the Docker client.

func (*SDKDockerProvider) ConnectNetwork added in v0.12.0

func (p *SDKDockerProvider) ConnectNetwork(ctx context.Context, networkID, containerID string) error

ConnectNetwork connects a container to a network.

func (*SDKDockerProvider) CopyContainerLogs added in v1.0.0

func (p *SDKDockerProvider) CopyContainerLogs(
	ctx context.Context, containerID string, stdout, stderr io.Writer, opts ContainerLogsOptions,
) error

CopyContainerLogs copies container logs into stdout/stderr, letting the adapter demultiplex Docker's stream framing for non-TTY containers.

func (*SDKDockerProvider) CreateContainer added in v0.12.0

func (p *SDKDockerProvider) CreateContainer(ctx context.Context, config *domain.ContainerConfig, name string) (string, error)

CreateContainer creates a new container.

func (*SDKDockerProvider) CreateExec added in v0.12.0

func (p *SDKDockerProvider) CreateExec(ctx context.Context, containerID string, config *domain.ExecConfig) (string, error)

CreateExec creates an exec instance.

func (*SDKDockerProvider) CreateService added in v0.12.0

CreateService creates a new Swarm service.

func (*SDKDockerProvider) EnsureImage added in v0.12.0

func (p *SDKDockerProvider) EnsureImage(ctx context.Context, image string, forcePull bool) error

EnsureImage ensures an image is available, pulling if necessary.

func (*SDKDockerProvider) FindNetworkByName added in v0.12.0

func (p *SDKDockerProvider) FindNetworkByName(ctx context.Context, networkName string) ([]domain.Network, error)

FindNetworkByName finds networks by name.

func (*SDKDockerProvider) GetContainerLogs added in v0.12.0

func (p *SDKDockerProvider) GetContainerLogs(ctx context.Context, containerID string, opts ContainerLogsOptions) (io.ReadCloser, error)

GetContainerLogs retrieves container logs.

func (*SDKDockerProvider) HasImageLocally added in v0.12.0

func (p *SDKDockerProvider) HasImageLocally(ctx context.Context, image string) (bool, error)

HasImageLocally checks if an image exists locally.

func (*SDKDockerProvider) Info added in v0.12.0

Info returns Docker system info.

func (*SDKDockerProvider) InspectContainer added in v0.12.0

func (p *SDKDockerProvider) InspectContainer(ctx context.Context, containerID string) (*domain.Container, error)

InspectContainer inspects a container.

func (*SDKDockerProvider) InspectExec added in v0.12.0

func (p *SDKDockerProvider) InspectExec(ctx context.Context, execID string) (*domain.ExecInspect, error)

InspectExec inspects an exec instance.

func (*SDKDockerProvider) InspectService added in v0.12.0

func (p *SDKDockerProvider) InspectService(ctx context.Context, serviceID string) (*domain.Service, error)

InspectService returns detailed information about a service.

func (*SDKDockerProvider) ListContainers added in v0.12.0

func (p *SDKDockerProvider) ListContainers(ctx context.Context, opts domain.ListOptions) ([]domain.Container, error)

ListContainers lists containers matching the options.

func (*SDKDockerProvider) ListTasks added in v0.12.0

func (p *SDKDockerProvider) ListTasks(ctx context.Context, opts domain.TaskListOptions) ([]domain.Task, error)

ListTasks lists tasks matching the filter options.

func (*SDKDockerProvider) Ping added in v0.12.0

func (p *SDKDockerProvider) Ping(ctx context.Context) error

Ping pings the Docker daemon.

func (*SDKDockerProvider) PullImage added in v0.12.0

func (p *SDKDockerProvider) PullImage(ctx context.Context, image string) error

PullImage pulls an image.

func (*SDKDockerProvider) RemoveContainer added in v0.12.0

func (p *SDKDockerProvider) RemoveContainer(ctx context.Context, containerID string, force bool) error

RemoveContainer removes a container.

func (*SDKDockerProvider) RemoveService added in v0.12.0

func (p *SDKDockerProvider) RemoveService(ctx context.Context, serviceID string) error

RemoveService removes a service.

func (*SDKDockerProvider) RunExec added in v0.12.0

func (p *SDKDockerProvider) RunExec(
	ctx context.Context, containerID string, config *domain.ExecConfig, stdout, stderr io.Writer,
) (int, error)

RunExec executes a command and waits for completion.

func (*SDKDockerProvider) StartContainer added in v0.12.0

func (p *SDKDockerProvider) StartContainer(ctx context.Context, containerID string) error

StartContainer starts a container.

func (*SDKDockerProvider) StartExec added in v0.12.0

StartExec starts an exec instance.

func (*SDKDockerProvider) StopContainer added in v0.12.0

func (p *SDKDockerProvider) StopContainer(ctx context.Context, containerID string, opts domain.StopOptions) error

StopContainer stops a container. opts.Timeout overrides the daemon's default grace period (typically 10s); opts.Signal selects the termination signal (defaults to the image's STOPSIGNAL / SIGTERM). See domain.StopOptions and #234.

func (*SDKDockerProvider) SubscribeEvents added in v0.12.0

func (p *SDKDockerProvider) SubscribeEvents(ctx context.Context, filter domain.EventFilter) (<-chan domain.Event, <-chan error)

SubscribeEvents subscribes to Docker events.

func (*SDKDockerProvider) WaitContainer added in v0.12.0

func (p *SDKDockerProvider) WaitContainer(ctx context.Context, containerID string) (int64, error)

WaitContainer waits for a container to exit.

func (*SDKDockerProvider) WaitForServiceTasks added in v0.12.0

func (p *SDKDockerProvider) WaitForServiceTasks(ctx context.Context, serviceID string, timeout time.Duration) ([]domain.Task, error)

WaitForServiceTasks waits for all tasks of a service to reach a terminal state.

type SDKDockerProviderConfig added in v0.12.0

type SDKDockerProviderConfig struct {
	// Host is the Docker host address (e.g., "unix:///var/run/docker.sock")
	Host string
	// Logger for operation logging
	Logger *slog.Logger
	// MetricsRecorder for metrics tracking
	MetricsRecorder MetricsRecorder
	// AuthProvider for registry authentication (optional)
	AuthProvider ports.AuthProvider
	// NegotiateTimeout overrides the bound on the initial Docker API version
	// negotiation that runs in NewClientWithConfig. Zero or negative values
	// keep the adapter default (defaultNegotiateTimeout). Exposed primarily
	// so tests can drive the construction-time wedge path quickly.
	NegotiateTimeout time.Duration
}

SDKDockerProviderConfig configures the SDK provider.

type SchedulePolicy added in v1.1.0

type SchedulePolicy struct {
	// CatchUp runs one missed fire after a downtime (missed_fires: one).
	CatchUp bool
	// Queue keeps one fire that arrives while a run is in progress and runs
	// it afterwards (concurrency: queue). Without it such a fire is skipped.
	Queue bool
	// Revision identifies the schedule: expression, time zone and both
	// policies. A different revision starts the record afresh.
	Revision string
}

SchedulePolicy is how a job's schedule treats missed fires and overlap.

type SchedulePolicyProvider added in v1.1.0

type SchedulePolicyProvider interface {
	SchedulePolicy() (policy SchedulePolicy, ok bool)
}

SchedulePolicyProvider is implemented by jobs whose schedule entry may keep a record (ADR-005). ok is false for a job that keeps none.

type ScheduleRecordStore added in v1.1.0

type ScheduleRecordStore interface {
	GetSchedule(name string) (persist.Schedule, bool)
	PutSchedule(name string, r persist.Schedule) error
	RemoveSchedules(names ...string) error
	ScheduleNames() []string
}

ScheduleRecordStore keeps the schedule records of ADR-005. persist.Store implements it; each PutSchedule is one atomic write of the state file.

type Scheduler

type Scheduler struct {
	Jobs    []Job
	Removed []Job
	Logger  *slog.Logger
	// contains filtered or unexported fields
}

Scheduler owns the set of registered jobs and drives them through go-cron. It handles registration and removal, name-based lookup, enable/disable, manual triggering, the global middleware chain propagated to every job, retries, and a concurrency limit shared across all entries.

Construct it with NewScheduler or one of its variants; a zero value has no cron instance and cannot run jobs. Methods are safe for concurrent use, and the exported Jobs and Removed slices are mutated under the scheduler's own lock — copy them (GetActiveJobs, GetRemovedJobs) rather than ranging over them from another goroutine.

func NewScheduler

func NewScheduler(l *slog.Logger) *Scheduler

NewScheduler returns a Scheduler with default settings: no metrics recorder, go-cron's default minimum @every interval (1s), the real clock, and a limit of 10 concurrent jobs. It does not start the cron loop — call Start for that. Use NewSchedulerWithMetrics, NewSchedulerWithOptions or NewSchedulerWithClock to change those defaults.

func NewSchedulerWithClock added in v0.17.0

func NewSchedulerWithClock(l *slog.Logger, cronClock *CronClock) *Scheduler

NewSchedulerWithClock creates a scheduler with a fake clock for testing. This allows tests to control time advancement without real waits.

func NewSchedulerWithMetrics added in v0.13.0

func NewSchedulerWithMetrics(l *slog.Logger, metricsRecorder MetricsRecorder) *Scheduler

NewSchedulerWithMetrics creates a scheduler with metrics (deprecated: use NewSchedulerWithOptions)

func NewSchedulerWithOptions added in v0.17.0

func NewSchedulerWithOptions(l *slog.Logger, metricsRecorder MetricsRecorder, minEveryInterval time.Duration) *Scheduler

NewSchedulerWithOptions creates a scheduler with configurable minimum interval. minEveryInterval of 0 uses the library default (1s). Use negative value to allow sub-second.

func (*Scheduler) AddJob

func (s *Scheduler) AddJob(j Job) error

AddJob registers j under its configured name, equivalent to AddJobWithTags with no tags. See AddJobWithTags for the registration semantics and the errors returned.

func (*Scheduler) AddJobDisabled added in v1.1.0

func (s *Scheduler) AddJobDisabled(j Job) error

AddJobDisabled registers j already disabled: its cron entry is added paused, so go-cron never dispatches it, not even for run-on-startup. Adding the job and then calling DisableJob would leave a window in which it can start.

func (*Scheduler) AddJobWithTags added in v0.13.0

func (s *Scheduler) AddJobWithTags(j Job, tags ...string) error

AddJobWithTags adds a job with optional tags for categorization. Tags can be used to group, filter, and remove related jobs. All jobs — including @triggered/@manual/@none — are registered with go-cron. Triggered schedules use go-cron's native TriggeredSchedule whose Next() returns zero time, so the scheduler never fires them automatically. They can be executed on demand via RunJob() which delegates to go-cron's TriggerEntryByName().

func (*Scheduler) DisableJob added in v0.8.0

func (s *Scheduler) DisableJob(name string) error

DisableJob pauses the job so it won't be scheduled or triggered, but keeps it for later enabling. Uses go-cron's native PauseEntryByName for all job types including triggered schedules (which now all have cron entries).

Holding s.mu while calling go-cron's PauseEntryByName is safe from deadlock: go-cron's setPausedState acquires c.runningMu and sends a request to the run loop, which sets a boolean flag without calling back into ofelia's Scheduler. Job execution happens in separate goroutines that do not hold c.runningMu, and runWithCtx only acquires s.mu.RLock (compatible with the Lock held here).

func (*Scheduler) EnableJob added in v0.8.0

func (s *Scheduler) EnableJob(name string) error

EnableJob resumes a previously disabled/paused job. Uses go-cron's native ResumeEntryByName for all job types including triggered schedules.

Lock safety: same as DisableJob -- see its doc comment for rationale.

func (*Scheduler) Entries added in v0.8.0

func (s *Scheduler) Entries() []cron.Entry

Entries returns all scheduled cron entries.

func (*Scheduler) EntryByName added in v0.21.0

func (s *Scheduler) EntryByName(name string) cron.Entry

EntryByName returns a snapshot of the cron entry with the given name. Returns an invalid Entry (Entry.Valid() == false) if not found or if the scheduler's cron instance is nil.

func (*Scheduler) GetActiveJobs added in v0.21.0

func (s *Scheduler) GetActiveJobs() []Job

GetActiveJobs returns a copy of all active (non-disabled) jobs.

func (*Scheduler) GetAnyJob added in v0.21.0

func (s *Scheduler) GetAnyJob(name string) Job

GetAnyJob returns a job by name regardless of disabled state.

func (*Scheduler) GetDisabledJob added in v0.8.0

func (s *Scheduler) GetDisabledJob(name string) Job

GetDisabledJob returns a disabled/paused job by name.

func (*Scheduler) GetDisabledJobs added in v0.8.0

func (s *Scheduler) GetDisabledJobs() []Job

GetDisabledJobs returns a copy of all disabled/paused jobs.

func (*Scheduler) GetJob added in v0.8.0

func (s *Scheduler) GetJob(name string) Job

GetJob returns an active (non-disabled) job by name.

func (*Scheduler) GetJobSnapshot added in v1.0.0

func (s *Scheduler) GetJobSnapshot() (active, disabled, removed []Job)

GetJobSnapshot returns the active, disabled and removed job lists as they stood at one instant.

Calling GetActiveJobs, GetDisabledJobs and GetRemovedJobs in sequence takes three separate read locks, so a job disabled or removed between two of them appears in both lists or in neither. The dashboard renders the lists without deduplicating by name, so such a job showed as two rows until the next poll healed it.

func (*Scheduler) GetJobsByTag added in v0.13.0

func (s *Scheduler) GetJobsByTag(tag string) []Job

GetJobsByTag returns all jobs with the specified tag.

func (*Scheduler) GetRemovedJobs added in v0.8.0

func (s *Scheduler) GetRemovedJobs() []Job

GetRemovedJobs returns a copy of all jobs that were removed from the scheduler.

func (*Scheduler) GetUnschedulableJobs added in v0.29.0

func (s *Scheduler) GetUnschedulableJobs() map[string]string

GetUnschedulableJobs returns a copy of the jobs the scheduler refused, keyed by job name with the reason as the value. Empty means every job that was offered is registered.

func (*Scheduler) GlobalMaxRuntime added in v1.1.0

func (s *Scheduler) GlobalMaxRuntime() (time.Duration, <-chan struct{})

GlobalMaxRuntime returns the bound an inheriting job runs under now, and a channel that is closed when the value next changes.

func (*Scheduler) IsJobDisabled added in v1.1.0

func (s *Scheduler) IsJobDisabled(name string) bool

IsJobDisabled reports whether the named job is registered and disabled.

func (*Scheduler) IsJobRunning added in v0.20.0

func (s *Scheduler) IsJobRunning(name string) bool

IsJobRunning reports whether the named job has any invocations currently in flight. Returns false if no job with the given name exists or the scheduler has no cron instance.

func (*Scheduler) IsRemovedJobRunning added in v1.1.0

func (s *Scheduler) IsRemovedJobRunning(j Job) bool

IsRemovedJobRunning reports whether j was removed or replaced and its canceled run is still stopping. IsJobRunning cannot answer that: it asks by name, which after a removal finds no entry, or the replacement's.

func (*Scheduler) IsRunning

func (s *Scheduler) IsRunning() bool

IsRunning returns true if the scheduler is active. Delegates to go-cron's IsRunning() which is the authoritative source.

func (*Scheduler) MaxRuntimeFor added in v1.1.0

func (s *Scheduler) MaxRuntimeFor(j Job) time.Duration

MaxRuntimeFor returns the bound a run of j starting now runs under: the job's own max-runtime, else the current `[global] max-runtime` for a job that inherits it, else defaultJobMaxRuntime.

func (*Scheduler) Middlewares

func (c *Scheduler) Middlewares() []Middleware

func (*Scheduler) PruneScheduleRecords added in v1.1.0

func (s *Scheduler) PruneScheduleRecords(keep func(name string) bool)

PruneScheduleRecords removes unused schedule records. Unresolved workloads retain a guard until they end, also while their configuration is absent.

func (*Scheduler) RemoveJob

func (s *Scheduler) RemoveJob(j Job) error

RemoveJob deregisters j so it will not fire again, cancels a run in progress, drops the job from the active jobs and appends it to Removed. It does not wait for the canceled run to stop: until it has, IsRemovedJobRunning reports true for j, and a job registered under the same name skips its fires (see runGate). Removal is by name, so a job that was never registered is silently ignored. The error return is always nil and exists for API stability.

func (*Scheduler) RemoveJobsByTag added in v0.13.0

func (s *Scheduler) RemoveJobsByTag(tag string) int

RemoveJobsByTag removes all jobs with the specified tag. Returns the number of jobs removed.

func (*Scheduler) ResetMiddlewares added in v0.9.0

func (c *Scheduler) ResetMiddlewares(ms ...Middleware)

func (*Scheduler) RunJob added in v0.8.0

func (s *Scheduler) RunJob(_ context.Context, jobName string) error

RunJob manually triggers a job by name. The job is executed through go-cron's TriggerEntryByName, which means it benefits from the full middleware chain (retry, timeout, etc.) and proper concurrency tracking. Returns ErrJobNotFound if the job does not exist or is disabled.

Note: The context parameter is currently unused because go-cron's TriggerEntryByName does not accept a context. The job runs with its own internal context managed by go-cron. This means request-scoped cancellation is not supported for triggered executions.

func (*Scheduler) SetClock added in v0.17.0

func (s *Scheduler) SetClock(c Clock)

SetClock replaces the clock stored on the scheduler. It exists for tests and does not change the clock go-cron schedules with, which is fixed at construction — use NewSchedulerWithClock to drive scheduling from a fake clock.

func (*Scheduler) SetGlobalMaxRuntime added in v1.1.0

func (s *Scheduler) SetGlobalMaxRuntime(d time.Duration)

SetGlobalMaxRuntime sets `[global] max-runtime`, the bound of every job that inherits it. The value applies to the next run and to runs in progress: a run whose elapsed time already reaches the new value ends with ErrMaxTimeRunning. A value <= 0 means defaultJobMaxRuntime.

func (*Scheduler) SetMaxConcurrentJobs added in v0.10.1

func (s *Scheduler) SetMaxConcurrentJobs(maxJobs int)

SetMaxConcurrentJobs configures the maximum number of concurrent jobs. The limit is enforced by the go-cron middleware chain (MaxConcurrentSkip pattern). When the limit is reached, new job invocations are skipped.

This should be called before Start(); calling it on a running scheduler resizes the semaphore but in-flight jobs retain the previous channel.

func (*Scheduler) SetMetricsRecorder added in v0.10.1

func (s *Scheduler) SetMetricsRecorder(recorder MetricsRecorder)

SetMetricsRecorder installs the recorder used for retry metrics and stores it on the scheduler. It can be called at any time, including while running.

It does not retrofit the go-cron observability hooks (job start, completion, scheduling and workflow results): those are wired only when a recorder is passed at construction time, so pass one to NewSchedulerWithMetrics or NewSchedulerWithOptions if you want them.

func (*Scheduler) SetOnJobComplete added in v0.17.0

func (s *Scheduler) SetOnJobComplete(callback func(jobName string, success bool))

SetOnJobComplete registers a callback invoked after every job run with the job's name and whether it succeeded (no error and the execution not marked failed). Passing nil clears it. Only one callback is held; a second call replaces the first.

The callback runs synchronously on the job's own goroutine at the end of the run, so it must not block. It may be changed while the scheduler is running: each run snapshots it under the lock.

func (*Scheduler) SetScheduleStore added in v1.1.0

func (s *Scheduler) SetScheduleStore(store ScheduleRecordStore)

SetScheduleStore sets where schedule records are kept. Without one, no job keeps a record and every job behaves as before ADR-005.

func (*Scheduler) Start

func (s *Scheduler) Start() error

Start wires the job dependency graph into go-cron and starts the cron loop. It does not block — the loop runs on its own goroutine — and always returns nil, including for a scheduler with no jobs registered. A failure to build the dependency graph is logged rather than returned, so that one misconfigured dependency cannot take down scheduling for every other job.

Jobs configured to run on startup fire once here, dispatched by go-cron. Starting an already-running scheduler is handled by go-cron and does not double-start the loop.

func (*Scheduler) Stop

func (s *Scheduler) Stop() error

Stop stops the cron loop and blocks for up to DefaultStopTimeout (30s) while running jobs finish. It returns an error wrapping ErrSchedulerTimeout if they have not finished by then — the jobs are not killed and may still be running when it returns. Use StopWithTimeout for a different bound, or StopAndWait to wait indefinitely.

func (*Scheduler) StopAndWait added in v0.13.0

func (s *Scheduler) StopAndWait()

StopAndWait stops the scheduler and waits indefinitely for all jobs to complete.

func (*Scheduler) StopWithTimeout added in v0.13.0

func (s *Scheduler) StopWithTimeout(timeout time.Duration) error

StopWithTimeout stops the scheduler with a graceful shutdown timeout. It stops accepting new jobs, then waits up to the timeout for running jobs to complete. Returns nil if all jobs completed, or an error if the timeout was exceeded.

func (*Scheduler) UpdateJob added in v0.20.0

func (s *Scheduler) UpdateJob(name string, newSchedule string, newJob Job) error

UpdateJob atomically replaces the schedule and job implementation for an existing named entry using go-cron's UpdateEntryJobByName. Replacing the job cancels the old job's run in progress, and UpdateJob does not wait for it to stop: until it has, the new job skips its fires (see runGate).

Disabled jobs are updated in place and stay disabled: refusing them would force callers into remove+add, which resumes the job and files the old copy under Removed.

Returns ErrJobNotFound if no job with the given name exists.

func (*Scheduler) Use

func (c *Scheduler) Use(ms ...Middleware)

type ShutdownHook added in v0.10.1

type ShutdownHook struct {
	Name     string
	Priority int // Lower values execute first
	Hook     func(context.Context) error
}

ShutdownHook is a function to be called during shutdown

type ShutdownManager added in v0.10.1

type ShutdownManager struct {
	// contains filtered or unexported fields
}

ShutdownManager handles graceful shutdown of the application

func NewShutdownManager added in v0.10.1

func NewShutdownManager(logger *slog.Logger, timeout time.Duration) *ShutdownManager

NewShutdownManager creates a new shutdown manager

func (*ShutdownManager) Done added in v0.29.0

func (sm *ShutdownManager) Done() <-chan struct{}

Done returns a channel that's closed once every hook has run.

ShutdownChan only says shutdown *began* — it is closed before the first hook executes. Anything that ends the process must wait on this instead, or the later priority groups are killed mid-flight and never run at all.

func (*ShutdownManager) IsShuttingDown added in v0.10.1

func (sm *ShutdownManager) IsShuttingDown() bool

IsShuttingDown returns true if shutdown is in progress

func (*ShutdownManager) ListenForShutdown added in v0.10.1

func (sm *ShutdownManager) ListenForShutdown()

ListenForShutdown starts listening for shutdown signals

func (*ShutdownManager) RegisterHook added in v0.10.1

func (sm *ShutdownManager) RegisterHook(hook ShutdownHook)

RegisterHook registers a shutdown hook

func (*ShutdownManager) Shutdown added in v0.10.1

func (sm *ShutdownManager) Shutdown() error

Shutdown initiates graceful shutdown

func (*ShutdownManager) ShutdownChan added in v0.10.1

func (sm *ShutdownManager) ShutdownChan() <-chan struct{}

ShutdownChan returns a channel that's closed when shutdown starts

type SimpleMetricsRecorder added in v0.10.1

type SimpleMetricsRecorder struct {
	// contains filtered or unexported fields
}

SimpleMetricsRecorder provides a basic implementation of JobMetricsRecorder

func NewSimpleMetricsRecorder added in v0.10.1

func NewSimpleMetricsRecorder() *SimpleMetricsRecorder

NewSimpleMetricsRecorder creates a new simple metrics recorder

func (*SimpleMetricsRecorder) GetMetrics added in v0.10.1

func (smr *SimpleMetricsRecorder) GetMetrics() map[string]any

GetMetrics returns all recorded metrics

func (*SimpleMetricsRecorder) RecordJobExecution added in v0.10.1

func (smr *SimpleMetricsRecorder) RecordJobExecution(jobName string, success bool, duration time.Duration)

RecordJobExecution records job execution metrics

func (*SimpleMetricsRecorder) RecordMetric added in v0.10.1

func (smr *SimpleMetricsRecorder) RecordMetric(name string, value any)

RecordMetric records a generic metric

func (*SimpleMetricsRecorder) RecordRetryAttempt added in v0.10.1

func (smr *SimpleMetricsRecorder) RecordRetryAttempt(jobName string, attempt int, success bool)

RecordRetryAttempt records retry attempt metrics

type Ticker added in v0.17.0

type Ticker interface {
	C() <-chan time.Time
	Stop()
}

Ticker delivers ticks on a channel at a fixed interval, mirroring time.Ticker. Stop halts delivery but does not close the channel.

type Timer added in v0.17.0

type Timer interface {
	C() <-chan time.Time
	Stop() bool
	Reset(d time.Duration) bool
}

Timer represents a single event timer, compatible with go-cron's Timer interface. It provides the same operations as time.Timer.

type WorkloadChecker added in v1.1.0

type WorkloadChecker interface {
	WorkloadRunning(ctx context.Context, executionID string) (bool, error)
}

WorkloadChecker is implemented by jobs that can tell whether the workload of a run, identified by its execution ID, is still running. After a crash the scheduler uses it to keep the entry busy while such a run goes on.

Directories

Path Synopsis
adapters
docker
Package docker provides an adapter for the official Docker SDK.
Package docker provides an adapter for the official Docker SDK.
mock
Package mock provides mock implementations of the ports interfaces for testing.
Package mock provides mock implementations of the ports interfaces for testing.
Package composeproject loads a Compose project and turns the scheduled entries of its top-level `jobs:` into job definitions Ofelia can schedule, following ADR-004 (docs/adr/ADR-004-compose-jobs-as-job-source.md).
Package composeproject loads a Compose project and turns the scheduled entries of its top-level `jobs:` into job definitions Ofelia can schedule, following ADR-004 (docs/adr/ADR-004-compose-jobs-as-job-source.md).
Package domain contains SDK-agnostic domain models for Docker operations.
Package domain contains SDK-agnostic domain models for Docker operations.
Package persist stores the subset of scheduler state that originates from the web UI / REST API and that operators reasonably expect to survive a daemon restart (issue #593).
Package persist stores the subset of scheduler state that originates from the web UI / REST API and that operators reasonably expect to survive a daemon restart (issue #593).
Package ports defines the port interfaces for Docker operations.
Package ports defines the port interfaces for Docker operations.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL