github.com/rotari-dev/rotari/internal/executor

Overview

package executor // import "github.com/rotari-dev/rotari/internal/executor"

Package executor defines job execution contracts and scheduler adapters.

It owns the boundary for local process execution, scheduler submission,
scheduler status resolution, cancellation, suspension, and wrapper scripts.
It should execute or control jobs according to caller-provided specs without
deciding queue selection, dependency scheduling, retry policy, or run
finalization.

Constants

const TimeoutExitCode = model.TimeoutExitCode
    TimeoutExitCode is the exit code recorded for a job stopped by its timeout,
    matching GNU timeout.

Variables

var ErrJobNotRunning = errors.New("job is not running")
    ErrJobNotRunning reports a job directory that no executor owns.

var RunSettingNames = []string{"ssh", "slurm", "pbs", "lsf", "sge"}
    RunSettingNames lists the executors that take per-run settings, such as
    --slurm-concurrency.

var SSHCommandPath = "/usr/bin/ssh"
    SSHCommandPath is the ssh binary invoked to run remote jobs; overridable
    (e.g. in tests, or validateExecutorCommand's availability check) since it is
    not always at a fixed path.

Functions

func CancelJob(jobDir string, canceller Canceller) error
    CancelJob cancels the submitted job in jobDir through canceller after
    recording the cancel, since a scheduler may keep no result for a job deleted
    while queued.

func ExpandShellOptions(options []string) ([]string, error)
    ExpandShellOptions splits shell-quoted option strings (e.g. "-p short
    --cpus-per-task=2") into individual CLI arguments. Shared by any executor
    that accepts free-form option strings, and by cmd/rotari's queue validation,
    which checks option quoting before a run starts.

func LSFExplicitEnvironmentVariable(name string) bool
    LSFExplicitEnvironmentVariable reports variables omitted by LSF's documented
    `-env all` transfer rules. The run environment adapter adds caller values
    for these names to the job wrapper as a targeted correction.

func LoadSchedulerStatus(store state.Store, jobDir string) string
func LocalElsewhere(store state.Store, executor JobExecutor, runDir, jobDir string) error
    LocalElsewhere returns a *state.ElsewhereError when executor is the local
    executor and the job in jobDir runs on another host or in another PID
    namespace (COORD-1). The local executor signals jobs by PID, which is only
    meaningful in the host and namespace that spawned the process; a failed
    PID check there would misleadingly report "job is not running", so callers
    surface this before trying. The run's recorded host (context.json) and the
    job's own record (job.json, which attempts from an earlier rotari lack) must
    both place the job here.

func LocalJobIdentity(store state.Store, jobDir string) (state.ProcessIdentity, error)
    LocalJobIdentity is the process a local attempt recorded: its host,
    PID namespace, and start from job.json, and its PID from there or from the
    pid file. An attempt from an earlier rotari has only the pid file, and its
    identity names no host or namespace. Without a PID the job is not running.

func LocalProcessGroupAlive(jobDir string) (alive, known bool)
    LocalProcessGroupAlive reports whether the process group recorded by a local
    attempt may still exist, by the shared rule (state.ObserveProcessGroup).
    known is false when the PID record cannot be inspected, or when the job runs
    on another host or in another PID namespace, where its PID means nothing
    here. A group whose leader's PID was reused may still hold the original's
    descendants, so it counts as alive.

func MergeEnvironment(base, overrides []string) []string
func RecordCancellation(jobDir string) error
    RecordCancellation writes the marker that a job's wrapper and its final
    result read as an explicit cancel.

func RecordCancelledJob(jobDir string, job model.JobSpec, store state.Store) model.JobResult
func RejectArraySchedulerOptions(options []string, names ...string) error
    RejectArraySchedulerOptions rejects executor options that would conflict
    with the array-index flags rotari itself supplies (e.g. Slurm's --array),
    used both by array submission and by cmd/rotari's queue validation.

func RunLocalJob(runDir string, job model.JobSpec, store state.Store, logf func(string, ...any)) model.JobResult
func RunLogForward(args []string) int
    RunLogForward is an internal command used by wrappers only when a job has
    external --output or --error destinations. It runs the requested command,
    streaming each fd to the wrapper (for rotari's live attempt log) and to the
    configured destinations without requiring a tee executable on the host.

func SSHTarget(options []string) (string, []string, error)
    SSHTarget parses the SSH executor's options into a target host and the
    remaining ssh(1) options, shared by both job submission and cmd/rotari's
    up-front queue validation.

func SchedulerCommandHint(binary string, output []byte, err error) error
    SchedulerCommandHint clarifies two common causes of an opaque scheduler
    control command failure: the scheduler's client tools (scontrol/qsig/
    bstop/...) not being installed on this host -- e.g. a web/CLI host outside
    the cluster that only shares the state directory over NFS, where the
    raw "executable file not found in $PATH" is easy to mistake for the job
    itself not running -- and the command running fine but being rejected by
    the scheduler itself (e.g. suspending a job that is still queued/pending
    rather than actually running), where Go's generic "exit status 1" hides the
    scheduler's own explanation unless the command's output is folded in.

func SchedulerStateExitCode(value string) (int, bool)
func SchedulerStateTerminal(value string) bool
func ShellQuote(value string) string
func StatusWrapperScript(command []string, jobDir string, environment []string, workingDirectory, timeout string, envMode ...string) string
    StatusWrapperScript runs a job's command and records its progress in
    status.json. A positive timeout (a model.ParseTimeout duration) stops the
    command that long after it starts.

func StatusWrapperScriptWithDestinations(command []string, jobDir string, environment []string, workingDirectory, timeout, logMode, openMode string, outputPaths, errorPaths []string, envMode ...string) string
func StatusWrapperScriptWithLogForwarder(command []string, jobDir string, environment []string, workingDirectory, timeout, openMode string, outputPaths, errorPaths []string, helper string, envMode ...string) string
func TimeoutMessage(seconds int) string
    TimeoutMessage describes a job stopped by a timeout of seconds.

func WriteSchedulerStatus(store state.Store, jobDir, value string, now time.Time)

Types

type ArraySubmitter interface {
	SubmitArray(runDir string, jobs []model.JobSpec, options []string) ([]JobHandle, error)
}

type Canceller interface {
	Cancel(jobDir string) error
}

type ExecutionProber struct {
	// Has unexported fields.
}
    ExecutionProber is a bounded, read-only batch. It caches only SGE's whole
    queue listing, never the verdict for a particular attempt.

func NewExecutionProber(store state.Store, ctx context.Context) *ExecutionProber

func (probe *ExecutionProber) Assess(dir, backend string) model.RecoveryExecution
    Assess never treats an outcome file as proof of termination. Missing launch
    identities (including the acceptance/publication crash window) stay unknown.

type JobExecutor interface {
	Name() string
	// Submit returns once the job's executor owns it (Registry.Owner finds
	// it), so a cancel can reach it from then on.
	Submit(runDir string, job model.JobSpec, options []string) (JobHandle, error)
	Wait(runDir string, handle JobHandle) model.JobResult
}

type JobHandle struct {
	Job    model.JobSpec
	Native string
	// Has unexported fields.
}

type LSF struct {
	Store              state.Store
	Logf               func(string, ...any)
	SubmissionRetry    schedulerSubmissionRetryPolicy
	SubmissionSpacing  *schedulerSubmissionGate
	SubmissionInterval time.Duration
}
    LSF submits jobs to IBM LSF via bsub and tracks them with bjobs/bhist.

func NewLSF(store state.Store, logf func(string, ...any)) LSF

func (lsf LSF) Cancel(jobDir string) error

func (LSF) Name() string

func (lsf LSF) Resume(jobDir string) error

func (lsf LSF) Submit(runDir string, job model.JobSpec, options []string) (JobHandle, error)

func (lsf LSF) SubmitArray(runDir string, jobs []model.JobSpec, options []string) ([]JobHandle, error)

func (lsf LSF) Suspend(jobDir string) error

func (lsf LSF) Wait(runDir string, handle JobHandle) model.JobResult

func (lsf LSF) WithRunSettings(settings RunSettings) JobExecutor

type Local struct {
	Store state.Store
	Logf  func(string, ...any)
}

func NewLocal(store state.Store, logf func(string, ...any)) Local

func (local Local) Cancel(jobDir string) error
    Cancel records the request before signalling. A SIGTERM that reaches
    the wrapper between installing its traps and spawning the command can be
    deferred until that command finishes, so the wrapper also reads this marker
    around the command launch and stops there.

    A job can end between the moment a caller selects it and the signal,
    so a process group that is already gone is not an error: the recorded
    cancellation is all that is left to do.

func (Local) Name() string

func (local Local) Resume(jobDir string) error

func (local Local) Submit(runDir string, job model.JobSpec, options []string) (JobHandle, error)
    Submit starts the job, which can be cancelled once Submit returns.

func (local Local) Suspend(jobDir string) error

func (local Local) Wait(runDir string, handle JobHandle) model.JobResult
    Wait waits for the job that Submit started.

type PBS struct {
	Store              state.Store
	Logf               func(string, ...any)
	SubmissionRetry    schedulerSubmissionRetryPolicy
	SubmissionSpacing  *schedulerSubmissionGate
	SubmissionInterval time.Duration
}
    PBS submits jobs to a PBS/Torque scheduler via qsub and tracks them through
    qstat, mirroring the Slurm executor's submit/poll/accounting model.

func NewPBS(store state.Store, logf func(string, ...any)) PBS

func (pbs PBS) Cancel(jobDir string) error

func (PBS) Name() string

func (pbs PBS) Resume(jobDir string) error

func (pbs PBS) Submit(runDir string, job model.JobSpec, options []string) (JobHandle, error)

func (pbs PBS) SubmitArray(runDir string, jobs []model.JobSpec, options []string) ([]JobHandle, error)

func (pbs PBS) Suspend(jobDir string) error

func (pbs PBS) Wait(runDir string, handle JobHandle) model.JobResult

func (pbs PBS) WithRunSettings(settings RunSettings) JobExecutor

type Registry map[string]JobExecutor
    Registry maps executor names to executors.

func NewRegistry(store state.Store, logf func(string, ...any)) Registry
    NewRegistry returns the built-in executors. logf receives job submission and
    completion lines.

func (registry Registry) Known(name string) bool
    Known reports whether name is a registered executor.

func (registry Registry) Lookup(name string) (JobExecutor, bool)
    Lookup returns the executor registered under name.

func (registry Registry) Names() []string
    Names returns the registered executor names, sorted for stable output.

func (registry Registry) Owner(store state.Store, jobDir string) (JobExecutor, error)
    Owner determines which executor owns the job recorded in jobDir, based on
    the metadata each executor writes on submission. Every scheduler-style
    executor writes job.json with its own "executor" name, so job.json alone
    (not its mere existence) names the owner. New local jobs do too; legacy
    local jobs have a pid file.

type RunSettings struct {
	Concurrency      int           `json:"concurrency,omitempty"`
	Options          []string      `json:"options,omitempty"`
	SubmitInterval   time.Duration `json:"submit_interval,omitempty"`
	SubmitRetryLimit int           `json:"submit_retry_limit,omitempty"`
}

type RunSettingsConfigurer interface {
	WithRunSettings(RunSettings) JobExecutor
}
    RunSettingsConfigurer returns an executor copy configured for one run.
    Implementations must not mutate a shared registry instance.

type RunSettingsMap map[string]RunSettings
    RunSettingsMap holds per-run settings by executor name.

func (settings RunSettingsMap) Concurrency(name string, fallback int) int
    Concurrency returns the concurrency set for name, or fallback when none is.

func (settings RunSettingsMap) Options(name string, fallback []string) []string
    Options returns the options set for name, or fallback when none are.

type SGE struct {
	Store              state.Store
	Logf               func(string, ...any)
	SubmissionRetry    schedulerSubmissionRetryPolicy
	SubmissionSpacing  *schedulerSubmissionGate
	SubmissionInterval time.Duration
}
    SGE submits jobs through the common Grid Engine qsub/qstat/qacct commands.
    Array tasks are submitted independently so this does not depend on the
    differing native array support and job-id syntax across Grid Engine forks.

func NewSGE(store state.Store, logf func(string, ...any)) SGE

func (sge SGE) Cancel(jobDir string) error

func (SGE) Name() string

func (sge SGE) Resume(jobDir string) error

func (sge SGE) Submit(runDir string, job model.JobSpec, options []string) (JobHandle, error)

func (sge SGE) Suspend(jobDir string) error

func (sge SGE) Wait(runDir string, handle JobHandle) model.JobResult

func (sge SGE) WithRunSettings(settings RunSettings) JobExecutor

type SSH struct {
	Store state.Store
}
    SSH runs jobs on a remote host over ssh, tracking the local ssh client
    process for the job's lifetime.

func NewSSH(store state.Store) SSH

func (ssh SSH) Cancel(jobDir string) error

func (SSH) Name() string

func (ssh SSH) Submit(runDir string, job model.JobSpec, options []string) (JobHandle, error)

func (ssh SSH) Wait(runDir string, handle JobHandle) model.JobResult

type SchedulerEvent struct {
	At       string `json:"at"`
	Query    string `json:"query"`
	State    string `json:"state,omitempty"`
	Error    string `json:"error,omitempty"`
	ExitCode *int   `json:"exit_code,omitempty"`
}
    SchedulerEvent is one line of a job's scheduler_events.jsonl. Query is
    "queue", "accounting", or "result"; a queue or accounting event is written
    only when its outcome changes.

type SchedulerProbe struct {
	Command []string `json:"command"`
	Output  string   `json:"output"`
	Error   string   `json:"error,omitempty"`
}
    SchedulerProbe is the output of one read-only scheduler query.

func ProbeSchedulerJob(store state.Store, attemptDir string) []SchedulerProbe
    ProbeSchedulerJob runs the queue and accounting queries rotari polls with
    for the scheduler job recorded in attemptDir's job.json, and returns their
    raw output. A job without a scheduler job ID has none.

type SchedulerStatus struct {
	State     string `json:"state"`
	UpdatedAt string `json:"updated_at"`
}

type Slurm struct {
	Store              state.Store
	Logf               func(string, ...any)
	SubmissionRetry    schedulerSubmissionRetryPolicy
	SubmissionSpacing  *schedulerSubmissionGate
	SubmissionInterval time.Duration
}
    Slurm submits jobs to Slurm via sbatch and tracks them through squeue/sacct.
    See submitSlurmJob and waitSlurmJob for the details.

func NewSlurm(store state.Store, logf func(string, ...any)) Slurm

func (slurm Slurm) Cancel(jobDir string) error

func (Slurm) Name() string

func (slurm Slurm) Resume(jobDir string) error

func (slurm Slurm) Submit(runDir string, job model.JobSpec, options []string) (JobHandle, error)

func (slurm Slurm) SubmitArray(runDir string, jobs []model.JobSpec, options []string) ([]JobHandle, error)

func (Slurm) SupportsSparseArray() bool

func (slurm Slurm) Suspend(jobDir string) error

func (slurm Slurm) Wait(runDir string, handle JobHandle) model.JobResult

func (slurm Slurm) WithRunSettings(settings RunSettings) JobExecutor

type SparseArraySupporter interface {
	SupportsSparseArray() bool
}

type Suspender interface {
	Suspend(jobDir string) error
	Resume(jobDir string) error
}

type WrapperStatus struct {
	Phase      string   `json:"phase"`
	ExitCode   int      `json:"exit_code,omitempty"`
	Error      string   `json:"error,omitempty"`
	Hosts      []string `json:"hosts,omitempty"`
	StartedAt  string   `json:"started_at,omitempty"`
	FinishedAt string   `json:"finished_at,omitempty"`
}
    WrapperStatus is the contents of status.json, written by StatusWrapperScript
    as a job runs and read back by both the local and scheduler executors (and
    by cmd/rotari's show/web/run-summary code, which polls it directly).

func LoadWrapperStatus(store state.Store, path string) (WrapperStatus, bool)