Skip to content
Projects

slurm_script_generator.remote

Test local code on a cluster over ssh.

slurm-remote syncs the current project to a cluster with rsync, submits a batch script there with sbatch, follows the job and fetches results back. All compute goes through SLURM, never the login node, and status polling has a minimum interval so that the scheduler is not hammered.

The host and remote directory come from flags, the SLURM_REMOTE_HOST and SLURM_REMOTE_DIR environment variables, or a slurm-remote.json file in the project directory, in that order of precedence. SSH connections are multiplexed (ControlMaster) so that you authenticate once, also with 2FA.

Attributes

NameDescription
CONFIG_FILENo description.
DEFAULT_EXCLUDESNo description.
DEFAULT_REMOTE_DIRNo description.
FINAL_STATESNo description.
MIN_POLL_INTERVALNo description.
RUN_SCRIPTNo description.

Classes

NameDescription
RemoteConfigWhere and how to run on the cluster.

Functions

NameDescription
build_parserBuild the argument parser of slurm-remote.
cmd_fetchHandle slurm-remote fetch.
cmd_logsHandle slurm-remote logs.
cmd_runHandle slurm-remote run: sync, submit, wait, show the log, fetch.
cmd_statusHandle slurm-remote status.
cmd_submitHandle slurm-remote submit.
cmd_syncHandle slurm-remote sync.
fetchCopy files from the cluster project directory back, keeping layout.
job_log_pathReturn the stdout file of a job on the cluster.
job_stateReturn the state of a job, from squeue or else sacct.
load_configResolve the configuration from flags, environment and config file.
mainEntry point for the slurm-remote command-line tool.
make_command_scriptBuild a batch script that runs command with the pragmas of a script.
parse_job_idExtract the job id from sbatch --parsable output.
project_pathReturn the project's directory on the cluster.
remote_quoteQuote a remote path but keep a leading ~ expandable.
remote_runRun a command over ssh and capture its output.
rsync_commandBuild an rsync command that uses the shared ssh options.
runRun a command, optionally capturing text output.
ssh_commandBuild the ssh command that runs remotecommand* on the cluster.
ssh_optionsReturn the ssh options shared by ssh and rsync calls.
submitSync the project and submit script there.
syncRsync the project to the cluster.
waitPoll a job until it reaches a final state.

CONFIG_FILEattributemodule attribute#

CONFIG_FILE = 'slurm-remote.json'

DEFAULT_EXCLUDESattributemodule attribute#

DEFAULT_EXCLUDES = ('.git', '.venv', 'venv', '__pycache__', '*.pyc', 'node_modules', 'build', '*.egg-info')

DEFAULT_REMOTE_DIRattributemodule attribute#

DEFAULT_REMOTE_DIR = '~/slurm-remote'

FINAL_STATESattributemodule attribute#

FINAL_STATES = frozenset(
  {
    'BOOT_FAIL',
    'CANCELLED',
    'COMPLETED',
    'DEADLINE',
    'FAILED',
    'NODE_FAIL',
    'OUT_OF_MEMORY',
    'PREEMPTED',
    'REVOKED',
    'TIMEOUT'
  }
)

MIN_POLL_INTERVALattributemodule attribute#

MIN_POLL_INTERVAL = 15

RUN_SCRIPTattributemodule attribute#

RUN_SCRIPT = '.slurm-remote-run.sh'

RemoteConfigclassdataclass#

class RemoteConfig(host: str, remote_dir: str = DEFAULT_REMOTE_DIR, excludes: list[str] = lambda : list(DEFAULT_EXCLUDES)(), setup: list[str] = list(), multiplex: bool = True, poll_interval: int = 30)

Where and how to run on the cluster.

Attributes

NameTypeDescription
hoststrssh destination, e.g. a Host alias from ~/.ssh/config.
remote_dirstrDirectory on the cluster that holds one folder per project.
excludeslist[str]rsync exclude patterns for the sync.
setuplist[str]Shell lines (module load ...) put before a command given to run.
multiplexboolWhether to reuse one ssh connection for all calls.
poll_intervalintSeconds between status checks while waiting.

excludesattributeclass attributeinstance attribute#

excludes: list[str] = field(default_factory=lambda : list(DEFAULT_EXCLUDES))

hostattributeinstance attribute#

host: str

multiplexattributeclass attributeinstance attribute#

multiplex: bool = True

poll_intervalattributeclass attributeinstance attribute#

poll_interval: int = 30

remote_dirattributeclass attributeinstance attribute#

remote_dir: str = DEFAULT_REMOTE_DIR

setupattributeclass attributeinstance attribute#

setup: list[str] = field(default_factory=list)

build_parserfunction#

def build_parser() -> argparse.ArgumentParser

Build the argument parser of slurm-remote.

cmd_fetchfunction#

def cmd_fetch(args, config) -> int

Handle slurm-remote fetch.

cmd_logsfunction#

def cmd_logs(args, config) -> int

Handle slurm-remote logs.

cmd_runfunction#

def cmd_run(args, config) -> int

Handle slurm-remote run: sync, submit, wait, show the log, fetch.

cmd_statusfunction#

def cmd_status(args, config) -> int

Handle slurm-remote status.

cmd_submitfunction#

def cmd_submit(args, config) -> int

Handle slurm-remote submit.

cmd_syncfunction#

def cmd_sync(args, config) -> int

Handle slurm-remote sync.

fetchfunction#

def fetch(config: RemoteConfig, project_dir: str, paths: list[str], remote_absolute: bool = False) -> int

Copy files from the cluster project directory back, keeping layout.

Parameters

NameTypeDefaultDescription
configRemoteConfigrequiredThe remote configuration.
project_dirstrrequiredLocal project directory.
pathslist[str]requiredPaths relative to the remote project directory, or absolute remote paths when remote_absolute is set.
remote_absoluteboolFalseTreat paths as absolute remote paths and copy them into the project directory by file name.

Returns

int
The exit code of the last rsync.

job_log_pathfunction#

def job_log_path(config: RemoteConfig, project_dir: str, job_id: int) -> str

Return the stdout file of a job on the cluster.

job_statefunction#

def job_state(config: RemoteConfig, job_id: int) -> str

Return the state of a job, from squeue or else sacct.

Raises

RuntimeError
If neither command knows the job.

load_configfunction#

def load_config(project_dir: str, host: str | None = None, remote_dir: str | None = None, config_path: str | None = None) -> RemoteConfig

Resolve the configuration from flags, environment and config file.

Parameters

NameTypeDefaultDescription
project_dirstrrequiredThe local project directory, where the config file lives.
hoststr | NoneNonessh destination given on the command line.
remote_dirstr | NoneNoneRemote base directory given on the command line.
config_pathstr | NoneNoneAlternative path of the JSON config file.

Returns

RemoteConfig
The resolved configuration.

Raises

ValueError
If no host is configured anywhere.

mainfunction#

def main(argv: list[str] | None = None) -> int

Entry point for the slurm-remote command-line tool.

Parameters

NameTypeDefaultDescription
argvlist[str] | NoneNoneArguments to parse, defaulting to the process arguments.

Returns

int
The exit code.

make_command_scriptfunction#

def make_command_script(script_text: str, command: str, setup: list[str]) -> str

Build a batch script that runs command with the pragmas of a script.

Parameters

NameTypeDescription
script_textstrText of the batch script whose #SBATCH lines to keep.
commandstrThe shell command to run instead of the script’s body.
setuplist[str]Lines to put before the command.

Returns

str
The text of the new batch script.

parse_job_idfunction#

def parse_job_id(output: str) -> int

Extract the job id from sbatch --parsable output.

Raises

ValueError
If the output holds no job id.

project_pathfunction#

def project_path(config: RemoteConfig, project_dir: str) -> str

Return the project’s directory on the cluster.

One folder per local directory name, so separate worktrees do not overwrite each other.

remote_quotefunction#

def remote_quote(path: str) -> str

Quote a remote path but keep a leading ~ expandable.

remote_runfunction#

def remote_run(config: RemoteConfig, remote_command: str) -> subprocess.CompletedProcess

Run a command over ssh and capture its output.

rsync_commandfunction#

def rsync_command(config: RemoteConfig, source: str, destination: str, excludes: list[str], delete: bool = False, files: list[str] | None = None) -> list[str]

Build an rsync command that uses the shared ssh options.

runfunction#

def run(command: list[str], capture: bool = False) -> subprocess.CompletedProcess

Run a command, optionally capturing text output.

Raises

RuntimeError
If the executable (ssh or rsync) is not installed.

ssh_commandfunction#

def ssh_command(config: RemoteConfig, remote_command: str, tty: bool = False) -> list[str]

Build the ssh command that runs remote_command on the cluster.

ssh_optionsfunction#

def ssh_options(config: RemoteConfig) -> list[str]

Return the ssh options shared by ssh and rsync calls.

submitfunction#

def submit(config: RemoteConfig, project_dir: str, script: str, delete: bool = False) -> int

Sync the project and submit script there.

Parameters

NameTypeDefaultDescription
configRemoteConfigrequiredThe remote configuration.
project_dirstrrequiredLocal project directory.
scriptstrrequiredPath of the batch script, relative to project_dir.
deleteboolFalseRemove remote files that no longer exist locally.

Returns

int
The job id.

Raises

RuntimeError
If syncing or submitting fails.

syncfunction#

def sync(config: RemoteConfig, project_dir: str, delete: bool = False) -> int

Rsync the project to the cluster.

Returns

int
The exit code of rsync.

waitfunction#

def wait(config: RemoteConfig, job_id: int, sleep=time.sleep, report=None) -> str

Poll a job until it reaches a final state.

Parameters

NameTypeDefaultDescription
configRemoteConfigrequiredThe remote configuration, with the polling interval.
job_idintrequiredThe job to follow.
sleeptime.sleepFunction used to wait, replaceable in tests.
reportNoneFunction used to print state changes.

Returns

str
The final state.