scheduler

package
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 26, 2026 License: BSD-3-Clause Imports: 14 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/Torque, LSF, and HTCondor.

Supported Schedulers

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

Architecture

scheduler.go        Core interface, types, resource resolution, validation
registry.go         Thread-safe active scheduler singleton + debugMode
error.go            Structured error types
gpu.go              GPU compatibility database, tier matching, MIG profiles
script_helpers.go   Shared parsing/formatting helpers (memory, time, flags, job header/footer)
slurm.go            SLURM implementation
pbs.go              PBS/Torque implementation
lsf.go              LSF implementation
htcondor.go         HTCondor implementation

Interface

type Scheduler interface {
    IsAvailable() bool
    ReadScriptSpecs(scriptPath string) (*ScriptSpecs, error)
    CreateScriptWithSpec(spec *JobSpec, outputDir string) (string, error)
    Submit(scriptPath string, dependencyJobIDs []string) (string, error)
    GetClusterInfo() (*ClusterInfo, error)
    GetInfo() *SchedulerInfo
    GetJobResources() *ResourceSpec // from scheduler env vars; zero fields = not set
}

Key Types

ScriptSpecs — parsed job specification:

  • 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

ResourceSpec — compute geometry: Nodes, TasksPerNode, CpusPerTask, MemPerNodeMB, Time, Gpu, Exclusive

JobSpec — submission input: Name, Command, Specs, DepJobIDs, Metadata

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

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

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

// Submission
SubmitJob(sched, scriptPath, deps)  // single job
SubmitJobs(sched, jobs, outputDir)  // multi-job with dependencies

// Validation
ValidateAndConvertSpecs(specs)      // validates against cluster limits
ValidateGpuAvailability(gpu, nodes, info) // returns GpuValidationError with suggestions

Configurable Scheduler Defaults

Applied when a script omits resource directives. Set via SetSpecDefaults() at CLI init.

# ~/.config/condatainer/config.yaml
scheduler:
  nodes: 1
  tasks_per_node: 1
  ncpus_per_task: 2
  mem_per_node_mb: 8192
  time: "4h"

Normalized Environment Variables

Generated job scripts export these regardless of scheduler: NNODES, NTASKS, NTASKS_PER_NODE, NCPUS, NCPUS_PER_TASK, MEM_MB, MEM_GB

Error Types

  • ValidationError - IsValidationError(err) — fields: Field, Requested, Limit, Partition
  • GpuValidationError - IsGpuValidationError(err) — has Suggestions
  • ParseError, SubmissionError, ClusterError — checked with Is* helpers

Scheduler-Specific Notes

SLURM
  • GPU: --gres=gpu:type:count > --gpus-per-node > --gpus÷nodes > --gpus-per-task×tasks
  • Memory: --mem (per-node), --mem-per-cpu (×cpus), --mem-per-gpu (×gpu count)
  • Blacklisted flags (trigger passthrough): --gpus-per-socket, --sockets-per-node, --cores-per-socket, --threads-per-core, --ntasks-per-socket, --ntasks-per-core, --distribution
  • Cluster info from sinfo + scontrol
PBS
  • Resources: select=N:ncpus=M:mpiprocs=P:mem=Xgb:ngpus=G or nodes=N:ppn=M
  • Cluster info from pbsnodes -a
LSF
  • CPU: -n, memory: -M (KB), nodes: -R "span[hosts=N]"
  • GPU: -gpu "num=N:type=T" or -R "rusage[ngpus_physical=N]"
  • Custom rusage params beyond mem/ngpus are lost during parsing
  • Cluster info from bhosts -w
HTCondor
  • Parses native .sub files; executable field → ScriptSpecs.ScriptPath
  • Resource keys: request_cpus, request_memory, request_gpus, +MaxRuntime (seconds)
  • Generates .sub + .sh wrapper; always single-node; no dependency support

Single-Node Enforcement

CreateScriptWithSpec normalizes to single-node by default:

Scheduler Mechanism
SLURM --nodes=1 --ntasks=1
PBS select=1:ncpus=N
LSF span[hosts=1] + -n N
HTCondor inherently single-node

Multi-node: set Nodes > 1 in ScriptSpecs.

Dependency Formats

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

Documentation

Overview

Package scheduler provides a unified interface for HPC job schedulers

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrSchedulerNotAvailable indicates the scheduler is not available
	ErrSchedulerNotAvailable = errors.New("scheduler is not available")

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

	// ErrAlreadyInJob indicates we're already inside a scheduler job
	ErrAlreadyInJob = errors.New("already inside a scheduler job")

	// 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

Functions

func AddCustomGpuCompat

func AddCustomGpuCompat(compat GpuCompatibility)

AddCustomGpuCompat allows adding custom GPU compatibility rules Useful for site-specific GPU types not in the default database

func CheckAvailability

func CheckAvailability() bool

CheckAvailability checks if a scheduler is available on the system Returns true if a scheduler is available and we're not inside a job

func ClearActiveScheduler

func ClearActiveScheduler()

ClearActiveScheduler resets the active scheduler reference.

func EnsureMigProfileInDatabase

func EnsureMigProfileInDatabase(migType string)

EnsureMigProfileInDatabase adds a MIG profile to the GPU database if not already present This is called automatically when SLURM discovers new MIG profiles

func ExtractBaseGpuFromMigProfile

func ExtractBaseGpuFromMigProfile(migType string) string

ExtractBaseGpuFromMigProfile extracts the base GPU type from a MIG profile Examples:

nvidia_h100_80gb_hbm3_1g.10gb -> h100
a100_1g.5gb -> a100
nvidia_a30_24gb_4g.24gb -> a30

func ExtractMemoryFromMigProfile

func ExtractMemoryFromMigProfile(migType string) int

ExtractMemoryFromMigProfile extracts memory size in GB from a MIG profile name Examples:

nvidia_h100_80gb_hbm3_1g.10gb -> 10
a100_2g.10gb -> 10
nvidia_a100_40gb_1g.5gb -> 5

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 IsClusterError

func IsClusterError(err error) bool

IsClusterError checks if an error is a ClusterError

func IsGpuValidationError

func IsGpuValidationError(err error) bool

IsGpuValidationError checks if an error is a GpuValidationError

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 IsMigProfile

func IsMigProfile(gpuType string) bool

IsMigProfile checks if a GPU type string is a MIG profile MIG profiles contain dots and underscores (e.g., nvidia_h100_80gb_hbm3_1g.10gb)

func IsParseError

func IsParseError(err error) bool

IsParseError checks if an error is a ParseError

func IsPassthrough added in v1.2.0

func IsPassthrough(specs *ScriptSpecs) bool

IsPassthrough reports having directives but no valid resource spec.

func IsSubmissionError

func IsSubmissionError(err error) bool

IsSubmissionError checks if an error is a SubmissionError

func IsValidationError

func IsValidationError(err error) bool

IsValidationError checks if an error is a ValidationError

func NormalizeGpuType

func NormalizeGpuType(gpuType string) string

NormalizeGpuType normalizes GPU type strings to canonical form

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. All counts default to 1 when rs is nil or unset.

  • NNODES — number of nodes
  • NTASKS_PER_NODE — tasks (MPI ranks) per node
  • NTASKS — total tasks (NNODES × NTASKS_PER_NODE)
  • NCPUS — CPUs per node (CpusPerTask × TasksPerNode, PBS-style)
  • NCPUS_PER_TASK — CPUs per task (SLURM-style --cpus-per-task)
  • MEM / MEM_MB / MEM_GB — included only when MemPerNodeMB > 0

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.

func SetSpecDefaults added in v1.2.0

func SetSpecDefaults(d ResourceSpec)

SetSpecDefaults overrides the default values used by ReadScriptSpecs.

func SubmitJob

func SubmitJob(scheduler Scheduler, scriptPath string, dependencyJobIDs []string) (string, error)

SubmitJob submits a single job and returns its job ID

func SubmitJobs

func SubmitJobs(scheduler Scheduler, jobs []*JobSpec, outputDir string) (map[string]string, error)

SubmitJobs submits multiple jobs with dependency chains and returns their job IDs

func SubmitWithDependencies

func SubmitWithDependencies(scheduler Scheduler, jobs []*JobSpec, outputDir string) (map[string]string, error)

SubmitWithDependencies submits multiple jobs with dependency chain

func ValidateAndConvertSpecs added in v1.2.0

func ValidateAndConvertSpecs(specs *ScriptSpecs) error

ValidateAndConvertSpecs validates job specs against cluster limits. Returns a descriptive error if any resource exceeds the partition limit. Never modifies specs in-place. Returns nil if cluster info is unavailable (validation skipped).

func ValidateGpuAvailability

func ValidateGpuAvailability(requestedSpec *GpuSpec, nodes int, info *ClusterInfo) error

ValidateGpuAvailability checks if the requested GPU is available. nodes is the number of nodes; requestedSpec.Count is per-node. Returns nil if available, or an error with suggestions if not.

func ValidateScript

func ValidateScript(scheduler Scheduler, scriptPath string) error

ValidateScript validates a script's specs against cluster limits

func ValidateSpecs

func ValidateSpecs(specs *ScriptSpecs, limits *ResourceLimits) error

ValidateSpecs validates job specs against cluster limits. Skips validation when specs.Spec is nil (passthrough mode).

func WriteScript

func WriteScript(scheduler Scheduler, jobSpec *JobSpec, outputDir string) (string, error)

WriteScript creates a batch script with the given specifications This is an alias for CreateScriptWithSpec for convenience

Types

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 DependencyError

type DependencyError struct {
	JobName       string   // Job name
	MissingDepIDs []string // Missing dependency job IDs
}

DependencyError represents an error with job dependencies

func NewDependencyError

func NewDependencyError(jobName string, missingDepIDs []string) *DependencyError

NewDependencyError creates a new DependencyError

func (*DependencyError) Error

func (e *DependencyError) Error() string

type GpuCompatibility

type GpuCompatibility struct {
	Type        string   // GPU type (e.g., "h100", "a100")
	Tier        GpuTier  // Performance tier
	Compute     float64  // Compute capability (e.g., 8.0, 9.0)
	MemoryGB    int      // Typical memory in GB
	Aliases     []string // Alternative names for this GPU
	UpgradeTo   []string // Better GPUs that can substitute this one
	DowngradeTo []string // Fallback GPUs if this is unavailable
}

GpuCompatibility defines GPU compatibility rules and performance tiers

func GetGpuInfo

func GetGpuInfo(gpuType string) (GpuCompatibility, bool)

GetGpuInfo returns information about a specific GPU type

type GpuConversionOption

type GpuConversionOption struct {
	OriginalSpec  *GpuSpec // Original GPU request
	SuggestedSpec *GpuSpec // Suggested GPU to use
	Available     int      // Number of this GPU type available
	Total         int      // Total number of this GPU type
	Partition     string   // Partition where this GPU is available
	IsUpgrade     bool     // True if suggested GPU is better than original
	IsDowngrade   bool     // True if suggested GPU is worse than original
	Reason        string   // Explanation for this suggestion
}

GpuConversionOption represents a possible GPU conversion/fallback

func FindCompatibleGpu

func FindCompatibleGpu(requestedSpec *GpuSpec, nodes int, info *ClusterInfo) ([]*GpuConversionOption, error)

FindCompatibleGpu finds compatible GPU alternatives when requested type is unavailable. nodes is the number of nodes in the job; requestedSpec.Count is per-node. Availability checks compare against Count * nodes (total GPUs needed). SuggestedSpec.Count is also per-node (same as requested).

Example

Example function demonstrating GPU conversion workflow

clusterInfo := &ClusterInfo{
	AvailableGpus: []GpuInfo{
		{Type: "h100", Total: 8, Available: 4, Partition: "gpu-high"},
		{Type: "a100", Total: 16, Available: 8, Partition: "gpu-standard"},
		{Type: "v100", Total: 32, Available: 16, Partition: "gpu-standard"},
	},
}

requestedSpec := &GpuSpec{
	Type:  "v100",
	Count: 2,
}

options, err := FindCompatibleGpu(requestedSpec, 1, clusterInfo)
if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

fmt.Printf("Found %d compatible GPU options:\n", len(options))
for i, opt := range options {
	status := "MATCH"
	if opt.IsUpgrade {
		status = "UPGRADE"
	} else if opt.IsDowngrade {
		status = "DOWNGRADE"
	}

	fmt.Printf("%d. %s x%d [%s] - %d available\n",
		i+1, opt.SuggestedSpec.Type, opt.SuggestedSpec.Count, status, opt.Available)
}
Output:
Found 1 compatible GPU options:
1. v100 x2 [MATCH] - 16 available

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

func FindAvailableGpuTypes

func FindAvailableGpuTypes(info *ClusterInfo) []GpuInfo

FindAvailableGpuTypes returns all GPU types available on 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.

func ConvertGpuSpec

func ConvertGpuSpec(requestedSpec *GpuSpec, nodes int, info *ClusterInfo) (*GpuSpec, error)

ConvertGpuSpec converts a GPU spec to use an available GPU type. nodes is the number of nodes; requestedSpec.Count is per-node. Returns the best available option or an error if no GPUs are available.

Example

Example demonstrating automatic GPU conversion

clusterInfo := &ClusterInfo{
	AvailableGpus: []GpuInfo{
		{Type: "a100", Total: 16, Available: 8, Partition: "gpu"},
		{Type: "v100", Total: 32, Available: 16, Partition: "gpu"},
	},
}

requestedSpec := &GpuSpec{
	Type:  "p100", // Not available
	Count: 2,
}

convertedSpec, err := ConvertGpuSpec(requestedSpec, 1, clusterInfo)
if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

fmt.Printf("Requested: %s x%d\n", requestedSpec.Type, requestedSpec.Count)
fmt.Printf("Converted to: %s x%d\n", convertedSpec.Type, convertedSpec.Count)
Output:
Requested: p100 x2
Converted to: v100 x2

type GpuTier

type GpuTier int

GpuTier represents the performance tier of GPUs for compatibility matching

const (
	TierUnknown GpuTier = iota
	TierEntry           // Consumer/Entry-level GPUs
	TierMid             // Mid-range GPUs (P100, V100, T4, etc.)
	TierHigh            // High-end GPUs (A100, H100, etc.)
)

type GpuValidationError

type GpuValidationError struct {
	RequestedType  string    // Requested GPU type
	RequestedCount int       // Requested GPU count
	Suggestions    []string  // Suggested alternative GPUs
	AvailableGpus  []GpuInfo // All available GPUs on cluster
}

GpuValidationError represents an error when requested GPU is not available

func NewGpuValidationError

func NewGpuValidationError(requestedType string, requestedCount int, suggestions []string, availableGpus []GpuInfo) *GpuValidationError

NewGpuValidationError creates a new GpuValidationError

func (*GpuValidationError) Error

func (e *GpuValidationError) Error() string

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) GetClusterInfo added in v1.2.0

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

GetClusterInfo retrieves HTCondor cluster configuration

func (*HTCondorScheduler) GetInfo added in v1.2.0

func (h *HTCondorScheduler) GetInfo() *SchedulerInfo

GetInfo returns information about the HTCondor scheduler

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) IsAvailable added in v1.2.0

func (h *HTCondorScheduler) IsAvailable() bool

IsAvailable checks if HTCondor is available and we're not 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.

func (*HTCondorScheduler) Submit added in v1.2.0

func (h *HTCondorScheduler) Submit(scriptPath string, dependencyJobIDs []string) (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
	Metadata       map[string]string // Additional metadata: ScriptPath, BuildSource, etc.
	OverrideOutput bool              // If true, always set Stdout/Stderr from Name (ignores script directives)
}

JobSpec represents specifications for submitting a batch job

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) GetClusterInfo added in v1.1.1

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

GetClusterInfo retrieves cluster configuration (GPUs, limits)

func (*LsfScheduler) GetInfo added in v1.1.1

func (l *LsfScheduler) GetInfo() *SchedulerInfo

GetInfo returns information about the LSF scheduler

func (*LsfScheduler) GetJobResources added in v1.2.0

func (s *LsfScheduler) GetJobResources() *ResourceSpec

GetJobResources reads allocated resources from LSF environment variables. Fields with value 0 were not exposed by LSF. Nodes and TasksPerNode are not available from LSF env vars.

func (*LsfScheduler) IsAvailable added in v1.1.1

func (l *LsfScheduler) IsAvailable() bool

IsAvailable checks if LSF is available and we're not 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, dependencyJobIDs []string) (string, error)

Submit submits an LSF job with optional dependency chain

type ParseError

type ParseError struct {
	Scheduler string // Scheduler name (e.g., "SLURM", "PBS")
	Line      int    // Line number where error occurred
	Content   string // Line content
	Reason    string // Reason for parse failure
}

ParseError represents an error parsing scheduler directives

func NewParseError

func NewParseError(scheduler string, line int, content string, reason string) *ParseError

NewParseError creates a new ParseError

func (*ParseError) Error

func (e *ParseError) Error() string

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/Torque 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) GetClusterInfo

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

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

func (*PbsScheduler) GetInfo

func (p *PbsScheduler) GetInfo() *SchedulerInfo

GetInfo returns information about the PBS scheduler

func (*PbsScheduler) GetJobResources added in v1.2.0

func (s *PbsScheduler) GetJobResources() *ResourceSpec

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

func (*PbsScheduler) IsAvailable

func (p *PbsScheduler) IsAvailable() bool

IsAvailable checks if PBS is available and we're not 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, dependencyJobIDs []string) (string, error)

Submit submits a PBS job with optional dependency chain

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).

func ReadMaxSpecs

func ReadMaxSpecs(scheduler Scheduler) (*ResourceLimits, error)

ReadMaxSpecs reads cluster information and returns the maximum resource limits Returns the most permissive limits across all partitions

type ResourceSpec added in v1.2.0

type ResourceSpec struct {
	Nodes        int           // Number of nodes
	TasksPerNode int           // MPI ranks / tasks per node
	CpusPerTask  int           // CPU threads per task
	MemPerNodeMB int64         // Total RAM per node in MB
	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) 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
	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).

type Scheduler

type Scheduler interface {
	// IsAvailable checks if the scheduler is available and we're not already in a job
	IsAvailable() 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 dependency chain
	// Returns the job ID assigned by the scheduler
	Submit(scriptPath string, dependencyJobIDs []string) (string, error)

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

	// GetInfo returns information about the scheduler
	GetInfo() *SchedulerInfo

	// 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
}

Scheduler defines the interface for job schedulers

func ActiveScheduler

func ActiveScheduler() Scheduler

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

func DetectScheduler

func DetectScheduler() (Scheduler, error)

DetectScheduler attempts to detect and return an available scheduler. Returns the scheduler instance if available, otherwise returns ErrSchedulerNotAvailable or ErrSchedulerNotFound.

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. This function returns a Scheduler instance if the scheduler binary is present, regardless of availability. Use DetectScheduler to require availability (not inside a job and submission enabled).

type SchedulerInfo

type SchedulerInfo struct {
	Type      string // Scheduler type (e.g., "SLURM", "PBS", "LSF")
	Binary    string // Path to scheduler binary (e.g., "/usr/bin/sbatch")
	Version   string // Scheduler version (if available)
	InJob     bool   // Whether we're currently inside a scheduled job
	Available bool   // Whether scheduler is available for job submission
}

SchedulerInfo holds information about the detected scheduler

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. Returns the detected scheduler type and any error.

func InitIfAvailable

func InitIfAvailable(preferredBin string) SchedulerType

InitIfAvailable attempts to initialize a scheduler if one is available. Unlike Init, this does not return an error if no scheduler is found. Returns the detected scheduler type (or SchedulerUnknown if none).

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
}

ScriptSpecs holds the full result of parsing a scheduler script.

func ReadScript

func ReadScript(scheduler Scheduler, scriptPath string) (*ScriptSpecs, error)

ReadScript reads and parses scheduler directives from a build script This is an alias for ReadScriptSpecs for convenience

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) GetClusterInfo

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

GetClusterInfo retrieves SLURM cluster configuration

func (*SlurmScheduler) GetInfo

func (s *SlurmScheduler) GetInfo() *SchedulerInfo

GetInfo returns information about the SLURM scheduler

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) IsAvailable

func (s *SlurmScheduler) IsAvailable() bool

IsAvailable checks if SLURM is available and we're not 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, dependencyJobIDs []string) (string, error)

Submit submits a SLURM job with optional dependency chain

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 ValidationError

type ValidationError struct {
	Field     string // Field that failed validation
	Requested int    // Requested value
	Limit     int    // Maximum allowed value
	Partition string // Partition where limit applies
}

ValidationError represents a validation error when specs exceed limits

func (*ValidationError) Error

func (e *ValidationError) Error() string

func (*ValidationError) Is

func (e *ValidationError) Is(target error) bool

Is allows errors.Is to match ValidationError

Jump to

Keyboard shortcuts

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