scheduler

package
v1.4.0 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2026 License: BSD-3-Clause Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

scheduler

HPC scheduler abstraction layer for job submission, script parsing, and resource management across SLURM, PBS, LSF, and HTCondor.

Supported Schedulers

Scheduler Binary Directive Status
SLURM sbatch #SBATCH Stable
PBS qsub #PBS Experimental
LSF bsub #BSUB Experimental
HTCondor condor_submit Native .sub format Experimental

Architecture

scheduler.go        Core interface, types, resource resolution
registry.go         Thread-safe active scheduler singleton + debugMode
error.go            Structured error types
exec.go             Shared runCommand helper with configurable timeout
script_helpers.go   Shared parsing/formatting helpers (memory, time, flags, job header/footer)
slurm.go / pbs.go / lsf.go / htcondor.go   Scheduler implementations

Interface

type Scheduler interface {
    IsAvailable() bool
    IsInsideJob() bool
    ReadScriptSpecs(scriptPath string) (*ScriptSpecs, error)
    CreateScriptWithSpec(spec *JobSpec, outputDir string) (string, error)
    Submit(scriptPath string, deps []Dependency) (string, error)
    GetClusterInfo() (*ClusterInfo, error)
    GetType() SchedulerType
    GetBinary() string
    GetVersion() string                          // slow — only call when result will be displayed
    GetJobResources() *ResourceSpec              // from scheduler env vars; zero fields = not set
    GetJobStatus(jobID string) (JobStatus, error)
    GetCurrentJobID() string
    GetTmpDir() string
}

Key Types

ScriptSpecs — parsed job specification:

  • ScriptPath string — absolute path of the parsed script (for HTCondor .sub: the executable)
  • HasDirectives bool — false when no #SBATCH/#PBS/#BSUB lines exist
  • Spec *ResourceSpec — resource geometry; nil in passthrough mode
  • Control RuntimeConfig — job name, stdout/stderr, email, partition
  • RawFlags []string — immutable audit log of all original directives
  • RemainingFlags []string — directives not absorbed by Spec or Control
  • ScriptType SchedulerType — scheduler type detected from script directives

ResourceSpec — compute geometry: Nodes, Ntasks, TasksPerNode (0 = not set / freely distributed), CpusPerTask, MemPerCpuMB, MemPerNodeMB, Time, Gpu, Exclusive

Memory field Source Meaning
MemPerCpuMB SLURM --mem-per-cpu; LSF rusage[mem=X] ÷ CpusPerTask; PBS multi-chunk + (uniform per-cpu mem) Per-CPU memory in MB
MemPerNodeMB SLURM --mem; PBS select=…:mem=X (per-node) Per-node total memory in MB

GetMemPerNodeMB() checks MemPerCpuMB × CpusPerTask × TasksPerNode first (requires TasksPerNode > 0); otherwise returns MemPerNodeMB (0 if not set).

GetMemPerTaskMB() checks MemPerCpuMB × CpusPerTask first; otherwise returns MemPerNodeMB ÷ TasksPerNode (treats 0 as 1). Returns 0 if no memory is specified.

JobSpec — submission input: Name, Command, Specs, DepJobIDs, Metadata, OverrideOutput bool, Array *ArraySpec

ArraySpec: InputFile, Count (non-empty lines), Limit (max concurrent), ArgCount, SampleArgs, BlankLines

Resource Spec Priority Chain

defaults  →  script directives (HasDirectives=true only)  →  job resources (non-zero fields)
ResolveResourceSpec(jobResources, scriptSpecs)              // uses GetSpecDefaults() as baseline
ResolveResourceSpecFrom(defaults, jobResources, scriptSpecs) // custom baseline
(*ResourceSpec).Override(other *ResourceSpec)               // in-place merge

Script Parsing

ReadScriptSpecsFromPath always returns non-nil *ScriptSpecs:

State HasDirectives Spec Meaning
No directives false non-nil No scheduler lines found
Normal true non-nil Parsed successfully
Passthrough true nil Directives found, resource parse failed

Key Functions

scheduler.Init("")                  // auto-detect and set active scheduler
scheduler.ActiveScheduler()         // get current scheduler

ReadScriptSpecsFromPath(path)       // always non-nil
HasSchedulerSpecs(specs)            // HasDirectives=true
IsPassthrough(specs)                // HasDirectives=true && Spec=nil

Normalized Environment Variables

Normalized variables are exported in the generated batch script for LSF and HTCondor (which lack sufficient native environment variables). For SLURM and PBS, they are computed on-demand when entering containers via condatainer run/exec.

Always Available
Variable Meaning Always Set
NNODES Number of nodes yes (default 1)
NTASKS Total MPI tasks yes (default 1)
NCPUS CPUs per task (= OMP_NUM_THREADS) yes (default 1)
OMP_NUM_THREADS OpenMP thread count yes (= NCPUS)
Conditionally Available
Variable OpenMP MPI Hybrid Free-Dist (no Nodes) Availability Logic
NTASKS_PER_NODE ✓ ✓ ✓ ✗ TasksPerNode > 0 (known layout)
MEM / MEM_GB ✓ ✓ ✓ ✓ Always if memory specified

Memory Variable Logic:

  • MEM is memory per task in MB — always available when memory is specified
    • From MemPerCpuMB: MEM = MemPerCpuMB × CpusPerTask
    • From MemPerNodeMB: MEM = MemPerNodeMB ÷ TasksPerNode (treats 0 as 1)
  • MEM_GB is MEM ÷ 1024 (integer)

Job Types:

  • OpenMP: 1 task, multiple CPUs per task (e.g., NNODES=1, NTASKS=1, NCPUS=8)
  • MPI: Multiple tasks, 1 CPU per task, fixed layout (e.g., NNODES=2, NTASKS=16, NTASKS_PER_NODE=8, NCPUS=1)
  • Hybrid: Multiple tasks, multiple CPUs per task, fixed layout (e.g., NNODES=2, NTASKS=8, NTASKS_PER_NODE=4, NCPUS=4)
  • Free-Dist (no Nodes): Only tasks, no node info (e.g., NTASKS=7, NCPUS=1, MEM=8192)

Ceiling Division for Non-Uniform Distribution:

When only get Nodes and Ntasks without TasksPerNode, CondaTainer will try to distribute the tasks by nodes as evenly as possible. (e.g. ntasks=7 and nodes=2 => tasks_per_node=4)

Implementation Notes
  • NTASKS uses rs.Ntasks directly when set; otherwise derives from Nodes × TasksPerNode
  • NTASKS_PER_NODE is absent only when node count is not specified:
    • SLURM: --ntasks=N without --nodes (free distribution across any nodes)
    • LSF: -n N without span[] directive (free distribution)
    • PBS: requires explicit node count; single-task jobs default to 1 node

PBS 2024 User Manual Page 118: Hybrid MPI-OpenMP Jobs

Per-Scheduler Environment Variables

Field SLURM PBS LSF
Job ID SLURM_JOB_ID PBS_JOBID LSB_JOBID
Nodes SLURM_JOB_NUM_NODES PBS_NUM_NODES (injected NNODES)
Total tasks SLURM_NTASKS PBS_NP / PBS_TASKNUM LSB_DJOB_NUMPROC / LSB_MAX_NUM_PROCESSORS (total slots)
Tasks per node SLURM_NTASKS_PER_NODE (derived) (injected NTASKS_PER_NODE)
CPUs per task SLURM_CPUS_PER_TASK NCPUS (cpus per task) (injected NCPUS)
Memory SLURM_MEM_PER_NODE (MB) → MemPerNodeMB PBS_VMEM (bytes) ÷ Nodes → MemPerNodeMB LSB_MAX_MEM_RUSAGE (KB) → MemPerCpuMB
GPU CUDA_VISIBLE_DEVICES count → Gpu CUDA_VISIBLE_DEVICES count → Gpu CUDA_VISIBLE_DEVICES count → Gpu
Array task index SLURM_ARRAY_TASK_ID PBS_ARRAY_INDEX LSB_JOBINDEX

HTCondor does not set standard resource environment variables.

Error Types

  • SubmissionError — job submission failed; includes scheduler name, job name, and output
  • ClusterError — cluster info query failed; includes scheduler name and operation
  • ScriptCreationError — batch script creation failed
  • TimeoutError — scheduler command timed out

Schedulers

Parallelism model fields: Nodes, Ntasks (0 = derive from Nodes × TasksPerNode), TasksPerNode (0 = free distribution), CpusPerTask.

Job Type Directives
Job type SLURM PBS LSF HTCondor
OpenMP (Ntasks=1, CpusPerTask=T) --ntasks=1 --cpus-per-task=T select=1:ncpus=T -n T -R "span[hosts=1]" request_cpus=T
MPI (CpusPerTask=1) --nodes=N --ntasks-per-node=M --cpus-per-task=1 select=N:ncpus=M:mpiprocs=M -n N*M -R "span[ptile=M]" (single-task)
Hybrid --nodes=N --ntasks-per-node=M --cpus-per-task=T select=N:ncpus=M*T:mpiprocs=M:ompthreads=T -n N*M -R "span[ptile=M] affinity[cores(T)]" (single-task)

Free-distribution (non-divisible Ntasks): SLURM emits --ntasks=Total; LSF emits -n Total; PBS uses two-chunk select=.

Slurm

Phase 2 resolution order (after collecting all directives):

  1. Nodes — --nodes
  2. GPU — --gres=gpu:type:count > --gpus-per-node > --gpus÷nodes > --gpus-per-task×tasks
  3. Tasks — --ntasks; --ntasks-per-node; --ntasks-per-gpu × gpuCount × nodes (requires GPU)
  4. CPU — --cpus-per-task; --cpus-per-gpu × gpuCount ÷ tasksPerNode
  5. Memory — --mem → MemPerNodeMB; --mem-per-cpu → MemPerCpuMB; --mem-per-gpu × gpu count → MemPerNodeMB
  6. Time — --time (independent)

Blacklisted (passthrough): --gpus-per-socket, --sockets-per-node, --cores-per-socket, --threads-per-core, --ntasks-per-socket, --ntasks-per-core, --distribution

PBS

PBS Pro/OpenPBS only; Torque not supported.

  • Job names (-N) are truncated to 15 characters at script generation time for safety.
  • Resources: select=N:ncpus=M:mpiprocs=P:mem=Xgb:ngpus=G
  • Old-style standalone resources (-l nodes=, -l ncpus=, etc.) → passthrough
  • Multi-chunk +: all chunks must share the same CpusPerTask = ncpus/mpiprocs; ngpus= in any chunk → passthrough
LSF
  • No node-count directive; nodes derived from -n / span[ptile=M]
  • If span[hosts=1], -n = total CPUs; otherwise -n = total tasks
  • Memory: rusage[mem=X] is the per-slot scheduling reservation → MemPerCpuMB = rusage_mem / affinity.cores (default 1); without -n → MemPerNodeMB
  • -M (per-process ulimit) is not used as a memory source when parsing; it passes through to RemainingFlags unchanged
  • On script generation, -M is emitted only when memory enforcement is configured (see below); any existing -M in RemainingFlags is suppressed to avoid duplicates
  • GPU: -gpu "num=N:gmodel=T" or -R "rusage[ngpus_physical=N]"

LSF -M generation (enforced memory limit):

-M is set to ceil(base × 110%) and only emitted when one of these env vars is set:

Env var -M semantics base value
LSB_MEMLIMIT_ENFORCE=y per-process RSS limit (LSF polls) memPerSlotMB
LSB_RESOURCE_ENFORCE=memory cgroup per-job enforcement; -M is secondary per-process ulimit memPerSlotMB
LSB_JOB_MEMLIMIT=y per-job aggregate limit (-M = total job memory) memPerSlotMB × totalSlots

totalSlots = CpusPerTask for OpenMP jobs; GetNtasks() for MPI/Hybrid jobs.

LSF -n semantics:

-R directive -n meaning Nodes
span[hosts=1] Total CPUs (= CpusPerTask) 1
span[ptile=M] Total tasks (= Ntasks) Ntasks / ptile
affinity[cores(T)] only Total tasks 0
(none) Total tasks 0
HTCondor
  • Parses native .sub files; executable → ScriptSpecs.ScriptPath
  • Resource keys: request_cpus, request_memory, request_gpus, +MaxRuntime (seconds)
  • Always single-task; no dependency support

Array Jobs

Pass JobSpec.Array = &ArraySpec{...} to CreateScriptWithSpec.

  • Scheduler directive silences per-subjob stdout (--output=/dev/null).
  • writeArrayBlock extracts the current line via sed -n "${_ARRAY_IDX}p" → ARRAY_ARGS; redirects output to {logDir}/{name}_{padded_idx}_{tag}.log (or .out/.err for separate output).
  • HTCondor uses queue array_args from {inputFile}.
Scheduler Directive
SLURM #SBATCH --array=1-N%limit
PBS #PBS -J 1-N%limit
LSF #BSUB -J name[1-N]%limit
HTCondor queue array_args from file

Dependency Formats

Submit accepts a []Dependency slice. Each Dependency has a Type (afterok, afternotok, afterany) and a list of JobIDs. HTCondor does not support dependencies (requires DAGMan) — passing a non-empty dep list returns an error.

Scheduler Format
SLURM --dependency=afterok:ID1:ID2
PBS -W depend=afterok:ID1:ID2
LSF -w "done(ID1) && done(ID2)"
HTCondor not supported (returns error)

Time Formats

Scheduler Format Example
SLURM D-HH:MM:SS or HH:MM:SS 1-12:00:00
PBS HH:MM:SS 04:00:00
LSF HH:MM 04:00
HTCondor integer seconds (+MaxRuntime) 14400

Scheduler Documentation

Documentation

Overview

Package scheduler provides a unified interface for HPC job schedulers

Index

Constants

View Source
const (
	DependencyAfterOK    = "afterok"    // Run only if all dependency jobs succeeded
	DependencyAfterNotOK = "afternotok" // Run only if any dependency job failed
	DependencyAfterAny   = "afterany"   // Run regardless of dependency job outcome
)

Dependency types for job submission.

Variables

View Source
var (
	// ErrSchedulerNotFound indicates the scheduler binary was not found
	ErrSchedulerNotFound = errors.New("scheduler binary not found in PATH")

	// ErrScriptNotFound indicates the script file was not found
	ErrScriptNotFound = errors.New("script file not found")

	// ErrInvalidScriptFormat indicates the script has invalid format
	ErrInvalidScriptFormat = errors.New("invalid script format")

	// ErrJobSubmissionFailed indicates job submission failed
	ErrJobSubmissionFailed = errors.New("job submission failed")

	// ErrJobIDParseFailed indicates parsing job ID from output failed
	ErrJobIDParseFailed = errors.New("failed to parse job ID from scheduler output")

	// ErrClusterInfoUnavailable indicates cluster information is not available
	ErrClusterInfoUnavailable = errors.New("cluster information unavailable")

	// ErrInvalidGpuSpec indicates GPU specification is invalid
	ErrInvalidGpuSpec = errors.New("invalid GPU specification")

	// ErrInvalidTimeFormat indicates time format is invalid
	ErrInvalidTimeFormat = errors.New("invalid time format")

	// ErrInvalidMemoryFormat indicates memory format is invalid
	ErrInvalidMemoryFormat = errors.New("invalid memory format")
)

Common errors

View Source
var DefaultCommandTimeout = 5 * time.Second

DefaultCommandTimeout is the maximum time to wait for a scheduler command to respond. Set this before calling any scheduler methods (e.g., from cmd/root.go after loading config). A value of 0 disables the timeout (command runs until completion).

Functions

func ActiveTmpDir added in v1.3.0

func ActiveTmpDir() string

ActiveTmpDir returns the scheduler-assigned node-local tmp directory for the current job, or "" if not inside a job or no tmp dir is exposed by the active scheduler.

func ClearActiveScheduler

func ClearActiveScheduler()

ClearActiveScheduler resets the active scheduler reference.

func CurrentJobID added in v1.3.0

func CurrentJobID() string

CurrentJobID returns the job ID of the currently running scheduler job, or "" if not inside a scheduler job or no scheduler is configured.

func HasSchedulerSpecs added in v1.2.0

func HasSchedulerSpecs(specs *ScriptSpecs) bool

HasSchedulerSpecs returns true if ScriptSpecs contains meaningful scheduler directives. This is used to determine if a script should be submitted to a scheduler, rather than relying on RawFlags which may be cleared during cross-scheduler translation.

func IsInsideJob

func IsInsideJob() bool

IsInsideJob checks if we're currently running inside a scheduler job. This is useful to avoid nested job submission.

func IsPassthrough added in v1.2.0

func IsPassthrough(specs *ScriptSpecs) bool

IsPassthrough reports having directives but no valid resource spec.

func ResourceEnvVars added in v1.2.0

func ResourceEnvVars(rs *ResourceSpec) []string

ResourceEnvVars returns KEY=VALUE strings for resource-related environment variables derived from rs.

Always emitted:

  • NNODES — number of nodes (default 1)
  • NTASKS — total tasks: rs.Ntasks when set directly, else Nodes×TasksPerNode
  • NCPUS — cpus per task (default 1); matches PBS semantics where NCPUS = OMP_NUM_THREADS = cpus per task
  • OMP_NUM_THREADS — cpus per task

Emitted only when TasksPerNode is known (> 0):

  • NTASKS_PER_NODE — tasks per node

Memory variables (emitted when memory is specified):

  • MEM — memory per task in MB; derived from MemPerCpuMB×CpusPerTask, or MemPerNodeMB÷TasksPerNode
  • MEM_GB — memory per task in GB (integer)

Note: Script parsing sets TasksPerNode using ceiling division when Nodes and Ntasks are specified but not evenly divisible (e.g., 7 tasks on 2 nodes → TasksPerNode=4), ensuring the generated script enforces the distribution assumed in memory allocation.

func SetActiveScheduler

func SetActiveScheduler(s Scheduler)

SetActiveScheduler configures the scheduler instance that the application should use. Passing nil clears any previously configured scheduler.

func SetDebugMode added in v1.2.0

func SetDebugMode(enabled bool)

SetDebugMode enables or disables debug output for scheduler operations. Call from cmd/root.go after loading config.

Types

type ArraySpec added in v1.3.0

type ArraySpec struct {
	InputFile  string   // Absolute path to input list (one entry per line)
	Count      int      // Non-empty line count; computed by cmd/run.go
	Limit      int      // Max concurrently running tasks (0 = unlimited)
	ArgCount   int      // Number of shell-split tokens per line (all lines must match)
	SampleArgs []string // Tokens from the first line, for dry-run display
	BlankLines []int    // 1-based line numbers of all blank lines (nil = none)
}

ArraySpec describes an input-file-driven array job. Each task processes one line from InputFile using the scheduler's native array mechanism. Limit=0 means no concurrency cap.

type ClusterError

type ClusterError struct {
	Scheduler string // Scheduler name
	Operation string // Operation that failed (e.g., "query GPUs", "get limits")
	Err       error  // Underlying error
}

ClusterError represents an error querying cluster information

func NewClusterError

func NewClusterError(scheduler string, operation string, err error) *ClusterError

NewClusterError creates a new ClusterError

func (*ClusterError) Error

func (e *ClusterError) Error() string

func (*ClusterError) Unwrap

func (e *ClusterError) Unwrap() error

type ClusterInfo

type ClusterInfo struct {
	AvailableGpus   []GpuInfo        // Available GPU types
	Limits          []ResourceLimits // Resource limits per partition
	MaxCpusPerNode  int              // Maximum CPUs available per node (from node info)
	MaxMemMBPerNode int64            // Maximum memory available per node in MB (from node info)
}

ClusterInfo holds cluster configuration information

type Dependency added in v1.3.0

type Dependency struct {
	Type   string   // DependencyAfterOK, DependencyAfterNotOK, or DependencyAfterAny
	JobIDs []string // Job IDs to depend on
}

Dependency represents a typed job dependency for submission.

type GpuInfo

type GpuInfo struct {
	Type      string // GPU type/model
	Total     int    // Total number of this GPU type
	Available int    // Currently available
	Partition string // Partition/queue name (optional)
}

GpuInfo holds information about available GPU types in the cluster

type GpuSpec

type GpuSpec struct {
	Type  string // GPU type/model (e.g., "h100", "a100", "v100")
	Count int    // Number of GPUs per node
	Raw   string // Raw GPU specification string from scheduler
}

GpuSpec holds GPU requirements parsed from scheduler directives. Count is per node (not total). Total GPUs = Count * ResourceSpec.Nodes.

type HTCondorScheduler added in v1.2.0

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

HTCondorScheduler implements the Scheduler interface for HTCondor EXPERIMENTAL: HTCondor is not tested on real clusters and may have edge cases. Feedback welcome.

func NewHTCondorScheduler added in v1.2.0

func NewHTCondorScheduler() (*HTCondorScheduler, error)

NewHTCondorScheduler creates a new HTCondor scheduler instance using condor_submit from PATH

func NewHTCondorSchedulerWithBinary added in v1.2.0

func NewHTCondorSchedulerWithBinary(condorSubmitBin string) (*HTCondorScheduler, error)

NewHTCondorSchedulerWithBinary creates an HTCondor scheduler using an explicit condor_submit path

func (*HTCondorScheduler) CreateScriptWithSpec added in v1.2.0

func (h *HTCondorScheduler) CreateScriptWithSpec(jobSpec *JobSpec, outputDir string) (string, error)

CreateScriptWithSpec generates an HTCondor submit description file and wrapper script

func (*HTCondorScheduler) GetBinary added in v1.3.0

func (h *HTCondorScheduler) GetBinary() string

func (*HTCondorScheduler) GetClusterInfo added in v1.2.0

func (h *HTCondorScheduler) GetClusterInfo() (*ClusterInfo, error)

GetClusterInfo retrieves HTCondor cluster configuration

func (*HTCondorScheduler) GetCurrentJobID added in v1.3.0

func (h *HTCondorScheduler) GetCurrentJobID() string

GetCurrentJobID returns the HTCondor job ID of the currently running job, or "".

func (*HTCondorScheduler) GetJobResources added in v1.2.0

func (h *HTCondorScheduler) GetJobResources() *ResourceSpec

GetJobResources reads allocated resources from HTCondor environment variables. HTCondor is always single-node; Nodes and TasksPerNode are not set.

func (*HTCondorScheduler) GetJobStatus added in v1.3.0

func (h *HTCondorScheduler) GetJobStatus(jobID string) (JobStatus, error)

GetJobStatus returns the current status of the given HTCondor job ID. Uses condor_q; returns JobStatusUnknown conservatively when condor_q is unavailable or times out. condor_q doesn't easily distinguish idle vs running without --format; presence = alive.

func (*HTCondorScheduler) GetTmpDir added in v1.3.0

func (h *HTCondorScheduler) GetTmpDir() string

GetTmpDir returns the HTCondor node-local tmp directory for the current job, or "".

func (*HTCondorScheduler) GetType added in v1.3.0

func (h *HTCondorScheduler) GetType() SchedulerType

func (*HTCondorScheduler) GetVersion added in v1.3.0

func (h *HTCondorScheduler) GetVersion() string

GetVersion returns the HTCondor version string, or "" on failure.

func (*HTCondorScheduler) IsAvailable added in v1.2.0

func (h *HTCondorScheduler) IsAvailable() bool

IsAvailable checks if the HTCondor binary is present on this system.

func (*HTCondorScheduler) IsInsideJob added in v1.3.0

func (h *HTCondorScheduler) IsInsideJob() bool

IsInsideJob returns true if the current process is running inside an HTCondor job.

func (*HTCondorScheduler) ReadScriptSpecs added in v1.2.0

func (h *HTCondorScheduler) ReadScriptSpecs(scriptPath string) (*ScriptSpecs, error)

ReadScriptSpecs parses an HTCondor submit file (.sub) in native key=value format. The executable line is extracted as the ScriptPath. Relative executable paths are resolved: first against initialdir (if set), then against the process CWD — matching real HTCondor behaviour and ensuring ScriptPath is always absolute.

func (*HTCondorScheduler) Submit added in v1.2.0

func (h *HTCondorScheduler) Submit(scriptPath string, deps []Dependency) (string, error)

Submit submits an HTCondor job with optional dependency chain

type JobSpec

type JobSpec struct {
	Name           string            // Job name (for temp and log file naming)
	Command        string            // Command to execute
	Specs          *ScriptSpecs      // Job specifications
	DepJobIDs      []string          // Job IDs this job depends on (always afterok, used by build chain)
	Metadata       map[string]string // Additional metadata: ScriptPath, BuildSource, etc.
	OverrideOutput bool              // If true, always set Stdout/Stderr from Name (ignores script directives)
	Array          *ArraySpec        // Non-nil → emit array job directives
}

JobSpec represents specifications for submitting a batch job

type JobStatus added in v1.3.0

type JobStatus int

JobStatus represents the current state of a scheduler job.

const (
	JobStatusUnknown JobStatus = iota // cannot determine (tool unavailable or timeout)
	JobStatusPending                  // queued, waiting for resources
	JobStatusRunning                  // currently executing on a node
	JobStatusDone                     // completed successfully
	JobStatusFailed                   // completed with failure or was cancelled
)

func (JobStatus) IsAlive added in v1.3.0

func (s JobStatus) IsAlive() bool

IsAlive returns true if the job is pending or running.

func (JobStatus) String added in v1.3.0

func (s JobStatus) String() string

String returns a human-readable job status label.

type LsfScheduler added in v1.1.1

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

LsfScheduler implements the Scheduler interface for IBM Spectrum LSF EXPERIMENTAL: LSF is not tested on real clusters and may have edge cases. Feedback welcome.

func NewLsfScheduler added in v1.1.1

func NewLsfScheduler() (*LsfScheduler, error)

NewLsfScheduler creates a new LSF scheduler instance using bsub from PATH

func NewLsfSchedulerWithBinary added in v1.1.1

func NewLsfSchedulerWithBinary(bsubBin string) (*LsfScheduler, error)

NewLsfSchedulerWithBinary creates an LSF scheduler using an explicit bsub path

func (*LsfScheduler) CreateScriptWithSpec added in v1.1.1

func (l *LsfScheduler) CreateScriptWithSpec(jobSpec *JobSpec, outputDir string) (string, error)

CreateScriptWithSpec generates an LSF batch script

func (*LsfScheduler) GetBinary added in v1.3.0

func (l *LsfScheduler) GetBinary() string

func (*LsfScheduler) GetClusterInfo added in v1.1.1

func (l *LsfScheduler) GetClusterInfo() (*ClusterInfo, error)

GetClusterInfo retrieves cluster configuration (GPUs, limits)

func (*LsfScheduler) GetCurrentJobID added in v1.3.0

func (l *LsfScheduler) GetCurrentJobID() string

GetCurrentJobID returns the LSF job ID of the currently running job, or "".

func (*LsfScheduler) GetJobResources added in v1.2.0

func (s *LsfScheduler) GetJobResources() *ResourceSpec

GetJobResources reads allocated resources from LSF environment variables and

LSF does not expose Nodes or TasksPerNode natively, so geometry is read from our injected NNODES / NTASKS_PER_NODE / NCPUS / NTASKS vars first.

LSB_DJOB_NUMPROC / LSB_MAX_NUM_PROCESSORS is the total number of allocated slots (= Ntasks × CpusPerTask). It is used as a Ntasks fallback when our injected NTASKS is absent; CpusPerTask (from NCPUS) is used to split the slot count correctly.

LSB_MAX_MEM_RUSAGE is per-slot (per-task) memory in KB → MemPerCpuMB.

func (*LsfScheduler) GetJobStatus added in v1.3.0

func (l *LsfScheduler) GetJobStatus(jobID string) (JobStatus, error)

GetJobStatus returns the current status of the given LSF job ID. Uses bjobs; returns JobStatusUnknown conservatively when bjobs is unavailable or times out.

func (*LsfScheduler) GetTmpDir added in v1.3.0

func (l *LsfScheduler) GetTmpDir() string

GetTmpDir returns the LSF node-local tmp directory for the current job, or "".

func (*LsfScheduler) GetType added in v1.3.0

func (l *LsfScheduler) GetType() SchedulerType

func (*LsfScheduler) GetVersion added in v1.3.0

func (l *LsfScheduler) GetVersion() string

GetVersion returns the LSF version string, or "" on failure.

func (*LsfScheduler) IsAvailable added in v1.1.1

func (l *LsfScheduler) IsAvailable() bool

IsAvailable checks if the LSF binary is present on this system.

func (*LsfScheduler) IsInsideJob added in v1.3.0

func (l *LsfScheduler) IsInsideJob() bool

IsInsideJob returns true if the current process is running inside an LSF job.

func (*LsfScheduler) ReadScriptSpecs added in v1.1.1

func (l *LsfScheduler) ReadScriptSpecs(scriptPath string) (*ScriptSpecs, error)

ReadScriptSpecs parses #BSUB directives from a build script using the shared pipeline.

func (*LsfScheduler) Submit added in v1.1.1

func (l *LsfScheduler) Submit(scriptPath string, deps []Dependency) (string, error)

type ParsedScript

type ParsedScript struct {
	Specs      *ScriptSpecs  // Normalized scheduler specifications
	ScriptType SchedulerType // Detected scheduler type from script directives
}

ParsedScript contains the normalized specs and detected script type

func ParseScriptAny

func ParseScriptAny(scriptPath string) (*ParsedScript, error)

ParseScriptAny parses scheduler directives from a script using the appropriate parser. It tries the current scheduler first, then falls back to other schedulers. This enables cross-scheduler compatibility (e.g., PBS can run SLURM scripts).

Returns:

  • ParsedScript with specs and detected type if directives found
  • nil ParsedScript if no scheduler directives found (not an error)
  • error if parsing fails

type PbsScheduler

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

PbsScheduler implements the Scheduler interface for PBS

NOTE: Only PBS Pro/OpenPBS is supported; Torque is not in the plan.

EXPERIMENTAL: PBS is not tested on real clusters and may have edge cases. Feedback welcome.

func NewPbsScheduler

func NewPbsScheduler() (*PbsScheduler, error)

NewPbsScheduler creates a new PBS scheduler instance using qsub from PATH

func NewPbsSchedulerWithBinary

func NewPbsSchedulerWithBinary(qsubBin string) (*PbsScheduler, error)

NewPbsSchedulerWithBinary creates a PBS scheduler using an explicit qsub path

func (*PbsScheduler) CreateScriptWithSpec

func (p *PbsScheduler) CreateScriptWithSpec(jobSpec *JobSpec, outputDir string) (string, error)

CreateScriptWithSpec generates a PBS batch script

func (*PbsScheduler) GetBinary added in v1.3.0

func (p *PbsScheduler) GetBinary() string

func (*PbsScheduler) GetClusterInfo

func (p *PbsScheduler) GetClusterInfo() (*ClusterInfo, error)

GetClusterInfo retrieves cluster configuration (GPUs, limits) Returns nil if information is not available

func (*PbsScheduler) GetCurrentJobID added in v1.3.0

func (p *PbsScheduler) GetCurrentJobID() string

GetCurrentJobID returns the PBS job ID of the currently running job, or "".

func (*PbsScheduler) GetJobResources added in v1.2.0

func (s *PbsScheduler) GetJobResources() *ResourceSpec

GetJobResources reads allocated resources from PBS environment variables. Fields with value 0 were not exposed by PBS.

func (*PbsScheduler) GetJobStatus added in v1.3.0

func (p *PbsScheduler) GetJobStatus(jobID string) (JobStatus, error)

GetJobStatus returns the current status of the given PBS job ID. Uses qstat -f; returns JobStatusUnknown conservatively when qstat is unavailable or times out.

func (*PbsScheduler) GetTmpDir added in v1.3.0

func (p *PbsScheduler) GetTmpDir() string

GetTmpDir returns the PBS node-local tmp directory for the current job, or "".

func (*PbsScheduler) GetType added in v1.3.0

func (p *PbsScheduler) GetType() SchedulerType

func (*PbsScheduler) GetVersion added in v1.3.0

func (p *PbsScheduler) GetVersion() string

GetVersion returns the PBS version string, or "" on failure.

func (*PbsScheduler) IsAvailable

func (p *PbsScheduler) IsAvailable() bool

IsAvailable checks if the PBS binary is present on this system.

func (*PbsScheduler) IsInsideJob added in v1.3.0

func (p *PbsScheduler) IsInsideJob() bool

IsInsideJob returns true if the current process is running inside a PBS job.

func (*PbsScheduler) ReadScriptSpecs

func (p *PbsScheduler) ReadScriptSpecs(scriptPath string) (*ScriptSpecs, error)

ReadScriptSpecs parses #PBS directives from a build script

func (*PbsScheduler) Submit

func (p *PbsScheduler) Submit(scriptPath string, deps []Dependency) (string, error)

type ResourceLimits

type ResourceLimits struct {
	MaxNodes        int           // Maximum nodes per job
	MaxCpusPerNode  int           // Maximum CPUs per node in this partition
	MaxMemMBPerNode int64         // Maximum memory per node in MB
	MaxGpus         int           // Maximum GPUs per job (total across all nodes)
	DefaultTime     time.Duration // Default walltime if not specified
	MaxTime         time.Duration // Maximum walltime (e.g., "7-00:00:00")
	Partition       string        // Partition/queue name these limits apply to
}

ResourceLimits holds scheduler resource limits per partition/queue. CPU and memory limits are per-node (matching how schedulers report them).

type ResourceSpec added in v1.2.0

type ResourceSpec struct {
	Nodes        int           // Number of nodes
	Ntasks       int           // Total MPI tasks (0 = not set; use Nodes*TasksPerNode)
	TasksPerNode int           // MPI ranks per node (0 = non-uniform distribution, e.g. multi-chunk PBS)
	CpusPerTask  int           // CPU threads per task (OpenMP)
	MemPerCpuMB  int64         // RAM per logical CPU in MB (SLURM --mem-per-cpu, LSF rusage[mem]÷CpusPerTask)
	MemPerNodeMB int64         // Total RAM per node in MB (SLURM --mem, PBS mem=)
	Gpu          *GpuSpec      // GPU requirements (nil = no GPU; Count = per node)
	Time         time.Duration // Job walltime limit
	Exclusive    bool          // Request exclusive node access (no other jobs on the same node)
}

ResourceSpec holds compute geometry for a job. A nil pointer means resource parsing failed — the job runs in passthrough mode.

func GetSpecDefaults added in v1.2.0

func GetSpecDefaults() ResourceSpec

GetSpecDefaults returns the current default values for ScriptSpecs.

func ResolveResourceSpec added in v1.2.0

func ResolveResourceSpec(jobResources *ResourceSpec, scriptSpecs *ScriptSpecs) *ResourceSpec

ResolveResourceSpec merges resources using the priority chain:

GetSpecDefaults() → scriptSpecs.Spec (when HasDirectives=true) → jobResources

Always returns a non-nil *ResourceSpec.

func ResolveResourceSpecFrom added in v1.2.0

func ResolveResourceSpecFrom(defaults ResourceSpec, jobResources *ResourceSpec, scriptSpecs *ScriptSpecs) *ResourceSpec

ResolveResourceSpecFrom merges resources using the priority chain:

defaults → scriptSpecs.Spec (when HasDirectives=true) → jobResources (non-zero fields)

Checks HasDirectives rather than Spec != nil: when a script has no directives, the parser fills Spec with GetSpecDefaults(), so checking only Spec != nil would silently replace the caller's defaults with scheduler defaults. Always returns a non-nil *ResourceSpec.

func (*ResourceSpec) GetMemPerNodeMB added in v1.3.0

func (rs *ResourceSpec) GetMemPerNodeMB() int64

GetMemPerNodeMB returns the effective memory per node in MB. Checks MemPerCpuMB × CpusPerTask × TasksPerNode first (requires TasksPerNode > 0), then returns MemPerNodeMB directly. Returns 0 if neither is set or geometry is insufficient to derive a value.

func (*ResourceSpec) GetMemPerTaskMB added in v1.3.0

func (rs *ResourceSpec) GetMemPerTaskMB() int64

GetMemPerTaskMB returns the effective memory per task in MB. Checks MemPerCpuMB × CpusPerTask first, then MemPerNodeMB ÷ TasksPerNode (treats 0 as 1). Returns 0 if no memory is specified.

func (*ResourceSpec) GetNtasks added in v1.3.0

func (rs *ResourceSpec) GetNtasks() int

GetNtasks returns the effective total task count. Prefers Ntasks if set; otherwise returns Nodes * TasksPerNode (minimum 1).

func (*ResourceSpec) IsMPI added in v1.3.0

func (rs *ResourceSpec) IsMPI() bool

IsMPI returns true if the job requests more than one MPI task.

func (*ResourceSpec) IsOpenMP added in v1.3.0

func (rs *ResourceSpec) IsOpenMP() bool

IsOpenMP returns true if the job requests more than one CPU per task.

func (*ResourceSpec) Override added in v1.2.0

func (rs *ResourceSpec) Override(other *ResourceSpec)

Override updates rs in-place with non-zero/non-nil fields from other. Fields in other that are zero/nil are skipped (rs retains its value). Safe to call with a nil other.

type RuntimeConfig added in v1.2.0

type RuntimeConfig struct {
	JobName      string // Identifier for the job
	WorkDir      string // Working directory for the job (e.g. initialdir in HTCondor, --chdir in SLURM)
	Stdout       string // Standard output file path
	Stderr       string // Standard error file path
	EmailOnBegin bool   // Notification on job start
	EmailOnEnd   bool   // Notification on job end
	EmailOnFail  bool   // Notification on job failure/abort
	MailUser     string // Target email/user for notifications (empty = submitting user)
	Partition    string // Partition/queue to submit to (cleared on cross-scheduler translation)
}

RuntimeConfig holds job-level control settings (name, I/O paths, notifications).

func (*RuntimeConfig) AbsStderr added in v1.3.0

func (rc *RuntimeConfig) AbsStderr() string

AbsStderr returns the absolute path for the Stderr file, resolved against WorkDir.

func (*RuntimeConfig) AbsStdout added in v1.3.0

func (rc *RuntimeConfig) AbsStdout() string

AbsStdout returns the absolute path for the Stdout file, resolved against WorkDir.

func (*RuntimeConfig) ResolvePath added in v1.3.0

func (rc *RuntimeConfig) ResolvePath(path string) string

ResolvePath returns path resolved against WorkDir when the path is relative. If WorkDir is empty, falls back to the process CWD via filepath.Abs. Already-absolute or empty paths are returned unchanged.

type Scheduler

type Scheduler interface {
	// IsAvailable checks if the scheduler binary is present on this system.
	IsAvailable() bool

	// IsInsideJob returns true if the current process is running inside a job
	// of this specific scheduler type, based on scheduler-set environment variables.
	IsInsideJob() bool

	// ReadScriptSpecs parses scheduler-specific directives from a build script
	// Returns ScriptSpecs with parsed scheduler directives (excludes #DEP and module directives)
	ReadScriptSpecs(scriptPath string) (*ScriptSpecs, error)

	// CreateScriptWithSpec generates a batch script with the given specifications
	// Returns the path to the created script
	CreateScriptWithSpec(spec *JobSpec, outputDir string) (string, error)

	// Submit submits a job script with optional typed dependency list.
	// Returns the job ID assigned by the scheduler.
	Submit(scriptPath string, deps []Dependency) (string, error)

	// GetClusterInfo retrieves cluster configuration (GPUs, limits)
	// Returns nil if information is not available
	GetClusterInfo() (*ClusterInfo, error)

	// GetType returns the scheduler type.
	GetType() SchedulerType

	// GetBinary returns the path to the scheduler binary.
	GetBinary() string

	// GetVersion runs the scheduler version command and returns the version string.
	// Returns "" on failure. This is slow — only call when the result will be displayed.
	GetVersion() string

	// GetJobResources reads allocated resources from scheduler environment variables.
	// Fields with value 0 were not exposed by the scheduler.
	// Returns nil if not running inside a job of this scheduler type.
	GetJobResources() *ResourceSpec

	// GetJobStatus returns the current status of the given job ID.
	// Returns JobStatusUnknown conservatively when the status cannot be determined
	// (tool unavailable, timeout). Returns JobStatusDone when definitely absent.
	GetJobStatus(jobID string) (JobStatus, error)

	// GetCurrentJobID returns the job ID of the currently running job for this
	// scheduler type, read from the scheduler-specific environment variable.
	// Returns "" if not inside a job of this type.
	GetCurrentJobID() string

	// GetTmpDir returns the scheduler-assigned node-local tmp directory for the
	// current job (e.g. SLURM_TMPDIR, PBS_TMPDIR). Returns "" if not in a job
	// or if the scheduler does not expose a tmp directory variable.
	GetTmpDir() string
}

Scheduler defines the interface for job schedulers

func ActiveScheduler

func ActiveScheduler() Scheduler

ActiveScheduler returns the currently configured scheduler instance (may be nil).

func DetectSchedulerWithBinary

func DetectSchedulerWithBinary(preferredBin string) (Scheduler, error)

DetectSchedulerWithBinary attempts to initialize a scheduler using a preferred binary path. If preferredBin is empty, detection falls back to the default discovery path. Returns a Scheduler instance if the scheduler binary is present, or ErrSchedulerNotFound. Use ActiveScheduler() to get the already-initialized instance instead of re-detecting.

type SchedulerType

type SchedulerType string

SchedulerType represents the type of job scheduler

const (
	SchedulerUnknown  SchedulerType = ""
	SchedulerSLURM    SchedulerType = "SLURM"
	SchedulerPBS      SchedulerType = "PBS"
	SchedulerLSF      SchedulerType = "LSF"
	SchedulerHTCondor SchedulerType = "HTCondor"
)

func DetectType

func DetectType() SchedulerType

DetectType returns the type of scheduler available on the system without initializing it. This is useful for checking what scheduler is available before deciding to use it.

func Init

func Init(preferredBin string) (SchedulerType, error)

Init auto-detects and initializes the active scheduler. If preferredBin is provided, it will be used instead of auto-detection. Type is derived from the concrete struct — no version subprocess is run. Returns the detected scheduler type and any error.

type ScriptCreationError

type ScriptCreationError struct {
	JobName string // Job name
	Path    string // Script path
	Err     error  // Underlying error
}

ScriptCreationError represents an error creating a batch script

func NewScriptCreationError

func NewScriptCreationError(jobName string, path string, err error) *ScriptCreationError

NewScriptCreationError creates a new ScriptCreationError

func (*ScriptCreationError) Error

func (e *ScriptCreationError) Error() string

func (*ScriptCreationError) Unwrap

func (e *ScriptCreationError) Unwrap() error

type ScriptSpecs

type ScriptSpecs struct {
	ScriptPath     string        // Absolute path of the parsed script (for HTCondor .sub: the executable)
	Spec           *ResourceSpec // Compute geometry (nil = resource parse failed → passthrough mode)
	Control        RuntimeConfig // Job control settings
	HasDirectives  bool          // True if any scheduler directive (#SBATCH, #PBS, etc.) was found
	RawFlags       []string      // ALL original directives — immutable audit log
	RemainingFlags []string      // Directives not absorbed by Spec or Control
	ScriptType     SchedulerType // Scheduler type detected from script directives
}

ScriptSpecs holds the full result of parsing a scheduler script.

func ReadScriptSpecsFromPath

func ReadScriptSpecsFromPath(scriptPath string) (*ScriptSpecs, error)

ReadScriptSpecsFromPath reads scheduler specs from a script file. It uses cross-scheduler translation: parses any scheduler format and returns normalized specs that can be used with the active scheduler.

If the script's scheduler type differs from the host scheduler, a warning message is returned (but not an error) to allow the build to proceed.

Always returns a non-nil *ScriptSpecs. When no directives are found, HasDirectives is false and Spec is filled with GetSpecDefaults() values (Nodes=1). Use HasDirectives and IsPassthrough to distinguish the three states.

func TryParseHTCondorScript added in v1.2.0

func TryParseHTCondorScript(scriptPath string) (*ScriptSpecs, error)

TryParseHTCondorScript attempts to parse an HTCondor submit file without requiring HTCondor binaries. This is a static parser that can work in any environment.

func TryParseLsfScript added in v1.1.1

func TryParseLsfScript(scriptPath string) (*ScriptSpecs, error)

TryParseLsfScript attempts to parse an LSF script without requiring LSF binaries. This is a static parser that can work in any environment.

func TryParsePbsScript

func TryParsePbsScript(scriptPath string) (*ScriptSpecs, error)

TryParsePbsScript attempts to parse a PBS script without requiring PBS binaries. This is a static parser that can work in any environment.

func TryParseSlurmScript

func TryParseSlurmScript(scriptPath string) (*ScriptSpecs, error)

TryParseSlurmScript attempts to parse a SLURM script without requiring SLURM binaries. This is a static parser that can work in any environment.

type SlurmScheduler

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

SlurmScheduler implements the Scheduler interface for SLURM

func NewSlurmScheduler

func NewSlurmScheduler() (*SlurmScheduler, error)

NewSlurmScheduler creates a new SLURM scheduler instance using sbatch from PATH

func NewSlurmSchedulerWithBinary

func NewSlurmSchedulerWithBinary(sbatchBin string) (*SlurmScheduler, error)

NewSlurmSchedulerWithBinary creates a SLURM scheduler using an explicit sbatch path

func (*SlurmScheduler) CreateScriptWithSpec

func (s *SlurmScheduler) CreateScriptWithSpec(jobSpec *JobSpec, outputDir string) (string, error)

CreateScriptWithSpec generates a SLURM batch script Returns the script path or any critical error.

func (*SlurmScheduler) GetBinary added in v1.3.0

func (s *SlurmScheduler) GetBinary() string

func (*SlurmScheduler) GetClusterInfo

func (s *SlurmScheduler) GetClusterInfo() (*ClusterInfo, error)

GetClusterInfo retrieves SLURM cluster configuration

func (*SlurmScheduler) GetCurrentJobID added in v1.3.0

func (s *SlurmScheduler) GetCurrentJobID() string

GetCurrentJobID returns the SLURM job ID of the currently running job, or "".

func (*SlurmScheduler) GetJobResources added in v1.2.0

func (s *SlurmScheduler) GetJobResources() *ResourceSpec

GetJobResources reads allocated resources from SLURM environment variables. Fields with value 0 were not exposed by SLURM.

func (*SlurmScheduler) GetJobStatus added in v1.3.0

func (s *SlurmScheduler) GetJobStatus(jobID string) (JobStatus, error)

GetJobStatus returns the current status of the given SLURM job ID. Uses squeue --format=%T; returns JobStatusUnknown conservatively when squeue is unavailable or times out. squeue only lists active jobs; empty output means the job has finished or is absent.

func (*SlurmScheduler) GetTmpDir added in v1.3.0

func (s *SlurmScheduler) GetTmpDir() string

GetTmpDir returns the SLURM node-local tmp directory for the current job, or "".

func (*SlurmScheduler) GetType added in v1.3.0

func (s *SlurmScheduler) GetType() SchedulerType

func (*SlurmScheduler) GetVersion added in v1.3.0

func (s *SlurmScheduler) GetVersion() string

GetVersion returns the SLURM version string, or "" on failure.

func (*SlurmScheduler) IsAvailable

func (s *SlurmScheduler) IsAvailable() bool

IsAvailable checks if the SLURM binary is present on this system.

func (*SlurmScheduler) IsInsideJob added in v1.3.0

func (s *SlurmScheduler) IsInsideJob() bool

IsInsideJob returns true if the current process is running inside a SLURM job.

func (*SlurmScheduler) ReadScriptSpecs

func (s *SlurmScheduler) ReadScriptSpecs(scriptPath string) (*ScriptSpecs, error)

ReadScriptSpecs parses #SBATCH directives from a build script

func (*SlurmScheduler) Submit

func (s *SlurmScheduler) Submit(scriptPath string, deps []Dependency) (string, error)

type SubmissionError

type SubmissionError struct {
	Scheduler string // Scheduler name
	JobName   string // Job name
	Output    string // Scheduler output
	Err       error  // Underlying error
}

SubmissionError represents an error during job submission

func NewSubmissionError

func NewSubmissionError(scheduler string, jobName string, output string, err error) *SubmissionError

NewSubmissionError creates a new SubmissionError

func (*SubmissionError) Error

func (e *SubmissionError) Error() string

func (*SubmissionError) Unwrap

func (e *SubmissionError) Unwrap() error

type TimeoutError added in v1.3.0

type TimeoutError struct {
	Scheduler string
	Operation string
	Timeout   time.Duration
}

TimeoutError represents a scheduler command that exceeded the configured timeout

func (*TimeoutError) Error added in v1.3.0

func (e *TimeoutError) Error() string

Jump to

Keyboard shortcuts

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