diff --git a/README.md b/README.md index 1a732ec..d2059af 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,13 @@ finally: manager.shutdown() ``` -`script_path` refers to a local Bash file whose contents are uploaded with the job. +When calling `submit_job()`, pass exactly one of `command`, `script_path`, +or `remote_script_path`. A local Bash file passed as +`script_path` is uploaded with the job. Use `remote_script_path` +for a Bash file accessible from the compute node. Relative paths start at +`working_directory`. Use `command` for Bash command text, such as +`command="python -m my_analysis"`. The worker executes command text directly +in Bash. For optional module loads or environment activation, pass `env_path="activate.sh"` with a local Bash activation script. Additional files used by the workload are not uploaded. Replace `working_directory` with an existing directory accessible on the compute node. diff --git a/slurm_manager/slurm_manager.py b/slurm_manager/slurm_manager.py index 38a86b3..7e55f7e 100644 --- a/slurm_manager/slurm_manager.py +++ b/slurm_manager/slurm_manager.py @@ -3,6 +3,7 @@ from __future__ import annotations import json +import posixpath import shlex import threading from collections.abc import Callable, Sequence @@ -201,9 +202,11 @@ class SlurmManager(Generic[_JobOptionsT]): def submit_job( # noqa: PLR0913 - submission options self, - script_path: str | Path, - env_path: str | Path | None = None, *, + command: str | None = None, + script_path: str | Path | None = None, + remote_script_path: str | Path | None = None, + env_path: str | Path | None = None, working_directory: str, job_options: _JobOptionsT | None = None, after_ok: JobFuture | Sequence[JobFuture] | None = None, @@ -211,11 +214,15 @@ class SlurmManager(Generic[_JobOptionsT]): callbacks: dict[Literal["log", "status", "heartbeat"], Callable[[SlurmMessage], None]] | None = None, ) -> JobFuture: - """Upload local Bash files and return a monitored, released Slurm job. + """Submit a Bash workload and return a monitored, released Slurm job. + + Supply exactly one of script_path, command, and remote_script_path. Args: - script_path (str | Path): Local Bash workload file whose contents are - uploaded. + command (str | None): Bash command text to execute on the compute node. + script_path (str | Path | None): Local Bash workload file to upload. + remote_script_path (str | Path | None): Bash file accessible on the compute + node. Relative paths are resolved from the job's working directory. env_path (str | Path | None): Optional local Bash activation file for workload-specific environment setup; None skips activation commands. working_directory (str): Absolute, existing compute-node directory in which @@ -236,8 +243,8 @@ class SlurmManager(Generic[_JobOptionsT]): Raises: FileNotFoundError: A local workload or activation file does not exist. - ValueError: The working directory, callback event names, or dependencies - are invalid. + ValueError: The workload, working directory, callback event names, or + dependencies are invalid. ValidationError: Resource or output options fail JobOptions validation. SlurmRestError: Submission or release fails. A known held job is cancelled on setup failure. @@ -245,8 +252,8 @@ class SlurmManager(Generic[_JobOptionsT]): Notes: The credential dotenv file stays local. Callbacks are registered before - release; only the working directory, worker path, and output paths refer to - compute nodes. + release. The working directory, worker path, remote script, and output + paths refer to compute nodes. """ if not working_directory.startswith("/"): raise ValueError("Working directory must be an absolute compute-node path") @@ -266,9 +273,12 @@ class SlurmManager(Generic[_JobOptionsT]): job["flags"] = [*job.get("flags", ()), "KILL_INVALID_DEPENDENCY"] job_id = str(uuid4()) script = self._build_job_script( - script_path, - env_path, - job_id, + command=command, + script_path=script_path, + remote_script_path=remote_script_path, + env_path=env_path, + working_directory=working_directory, + job_id=job_id, worker_path=self.worker_path, redis_address=self._redis_address, redis_tls=self._redis_tls, @@ -505,20 +515,26 @@ class SlurmManager(Generic[_JobOptionsT]): @staticmethod def _build_job_script( # noqa: PLR0913 - worker command and TLS configuration - script_path: str | Path, - env_path: str | Path | None, - job_id: str, *, + command: str | None = None, + script_path: str | Path | None = None, + remote_script_path: str | Path | None = None, + env_path: str | Path | None = None, + working_directory: str, + job_id: str, worker_path: str = "/usr/bin/bec-slurm-worker", redis_address: str = "localhost:6379", redis_tls: bool = True, ) -> str: - """Package local Bash file contents for the compute-node Go worker. + """Package a Bash workload for the compute-node Go worker. Args: - script_path (str | Path): Local Bash workload file whose contents are uploaded. + command (str | None): Bash command text to execute on the compute node. + script_path (str | Path | None): Local Bash workload file to upload. + remote_script_path (str | Path | None): Bash file accessible on the compute node. env_path (str | Path | None): Optional local Bash activation file for workload-specific environment setup; None skips activation commands. + working_directory (str): Absolute compute-node directory for relative paths. job_id (str): Opaque manager identifier used in Redis topic names. worker_path (str): Absolute path to the Go executable on compute nodes. redis_address (str): Redis host:port passed to the worker; no credentials are @@ -530,19 +546,32 @@ class SlurmManager(Generic[_JobOptionsT]): Raises: FileNotFoundError: A local script file is missing. - ValueError: The worker path is not an absolute compute-node path. + ValueError: The worker path or workload selection is invalid. Notes: - The payload contains the job ID and selected workload and activation scripts, - not the credential dotenv file. The job ID is kept out of process arguments. - Staging and cleanup belong to the worker. + The JSON payload carries the job ID, workload, and activation text. + The worker stages uploaded files and cleans them up after execution. """ if not worker_path.startswith("/"): raise ValueError("Worker path must be an absolute compute-node path") + if sum(source is not None for source in (script_path, command, remote_script_path)) != 1: + raise ValueError("Specify exactly one of script_path, command, and remote_script_path") + if script_path is not None: + workload = Path(script_path).read_text() + elif remote_script_path is not None: + remote_path = str(remote_script_path) + if not remote_path.strip(): + raise ValueError("remote_script_path must be nonempty") + remote_path = posixpath.join(working_directory, remote_path) + workload = shlex.join(["exec", "/bin/bash", "--", remote_path]) + elif command is not None and command.strip(): + workload = command + else: + raise ValueError("command must be nonempty") payload = json.dumps( { "job_id": job_id, - "script": Path(script_path).read_text(), + "script": workload, "activation": Path(env_path).read_text() if env_path is not None else "", } ) @@ -553,8 +582,10 @@ class SlurmManager(Generic[_JobOptionsT]): redis_address, f"--redis-tls={str(redis_tls).lower()}", ] - command = shlex.join(args) - return f"#!/bin/bash\nexec {command} <<'{delimiter}'\n{payload}\n{delimiter}\n" + if script_path is None: + args.append("--command") + worker_command = shlex.join(args) + return f"#!/bin/bash\nexec {worker_command} <<'{delimiter}'\n{payload}\n{delimiter}\n" ################################################ # Internal Monitoring # diff --git a/test/test_job_script.py b/test/test_job_script.py index c99d749..5e8f9d0 100644 --- a/test/test_job_script.py +++ b/test/test_job_script.py @@ -21,7 +21,12 @@ def test_local_scripts_are_passed_to_worker_as_json(tmp_path): ) worker.chmod(0o700) script = SlurmManager._build_job_script( - workload, activation, "job-id", worker_path=str(worker), redis_address="redis.example:6380" + script_path=workload, + env_path=activation, + working_directory="/remote/work", + job_id="job-id", + worker_path=str(worker), + redis_address="redis.example:6380", ) result = subprocess.run( ["bash"], input=script, capture_output=True, text=True, check=True, cwd=tmp_path @@ -39,13 +44,43 @@ def test_local_scripts_are_passed_to_worker_as_json(tmp_path): assert not (tmp_path / "must-not-exist").exists() +def test_relative_remote_script_path_stays_bound_to_the_job_directory(tmp_path): + remote_path = "-script $(touch unintended).sh" + batch_script = SlurmManager._build_job_script( + remote_script_path=remote_path, working_directory=str(tmp_path), job_id="job-id" + ) + assert "--command" in batch_script.splitlines()[1] + payload = json.loads(batch_script.splitlines()[2]) + + workload = tmp_path / remote_path + workload.write_text('printf "%s" "$0"\n') + activation_directory = tmp_path / "other" + activation_directory.mkdir() + (activation_directory / remote_path).write_text("echo wrong-script\n") + result = subprocess.run( + ["/bin/bash", "-c", payload["script"]], + cwd=activation_directory, + capture_output=True, + text=True, + check=True, + ) + assert result.stdout == str(workload) + assert not (activation_directory / "unintended").exists() + + def test_missing_local_file_fails_before_packaging(tmp_path): with pytest.raises(FileNotFoundError): - SlurmManager._build_job_script(tmp_path / "missing.sh", tmp_path / "activate.sh", "job-id") + SlurmManager._build_job_script( + script_path=tmp_path / "missing.sh", working_directory="/remote/work", job_id="job-id" + ) def test_worker_path_must_be_absolute(tmp_path): with pytest.raises(ValueError, match="absolute"): SlurmManager._build_job_script( - tmp_path / "unused.sh", tmp_path / "unused-env.sh", "job-id", worker_path="worker" + script_path=tmp_path / "unused.sh", + env_path=tmp_path / "unused-env.sh", + working_directory="/remote/work", + job_id="job-id", + worker_path="worker", ) diff --git a/test/test_slurm_manager.py b/test/test_slurm_manager.py index 359c469..04581d1 100644 --- a/test/test_slurm_manager.py +++ b/test/test_slurm_manager.py @@ -2,6 +2,7 @@ from __future__ import annotations +import json import threading import time from functools import partial @@ -45,7 +46,7 @@ def manager(): def submit(manager): return manager.submit_job( - Path(__file__).parent.parent / "examples/print_for_10s.sh", + script_path=Path(__file__).parent.parent / "examples/print_for_10s.sh", working_directory="/remote/node/work", ) @@ -400,7 +401,12 @@ def test_local_files_are_uploaded_without_mutating_options(manager, tmp_path): workload.write_text("#!/bin/bash\nprintf 'hello'\n") activation.write_text("module load redis\n") options = JobOptions(partition="hour", tasks=2, time_limit=5) - manager.submit_job(workload, activation, working_directory="/remote/work", job_options=options) + manager.submit_job( + script_path=workload, + env_path=activation, + working_directory="/remote/work", + job_options=options, + ) script, job = manager.rest_client.submit.call_args.args assert "hello" in script assert "module load redis" in script @@ -412,6 +418,22 @@ def test_local_files_are_uploaded_without_mutating_options(manager, tmp_path): assert job["time_limit"] == {"set": True, "number": 5} +def test_command_submission_passes_text_to_worker(manager): + manager.submit_job(command="printf 'hello world\\n'", working_directory="/remote/work") + + script, _ = manager.rest_client.submit.call_args.args + assert "--command" in script.splitlines()[1] + payload = json.loads(script.splitlines()[2]) + assert payload["script"] == "printf 'hello world\\n'" + + +@pytest.mark.parametrize("workload", [{}, {"command": "true", "script_path": "unused.sh"}]) +def test_submission_requires_exactly_one_workload(manager, workload): + with pytest.raises(ValueError, match="Specify exactly one"): + manager.submit_job(working_directory="/remote/work", **workload) + manager.rest_client.submit.assert_not_called() + + @pytest.mark.parametrize("tasks", [None, 1, 8]) def test_submission_preserves_explicit_tasks_for_per_node_layout(manager, tasks): options = ( @@ -421,7 +443,9 @@ def test_submission_preserves_explicit_tasks_for_per_node_layout(manager, tasks) ) manager.submit_job( - "examples/print_for_10s.sh", working_directory="/remote/work", job_options=options + script_path="examples/print_for_10s.sh", + working_directory="/remote/work", + job_options=options, ) _, job = manager.rest_client.submit.call_args.args @@ -440,7 +464,9 @@ def test_dependency_futures_use_scheduler_job_ids(manager, argument, kind, multi first = submit(manager) upstream = [first, submit(manager)] if multiple else first manager.submit_job( - "examples/print_for_10s.sh", working_directory="/remote/work", **{argument: upstream} + script_path="examples/print_for_10s.sh", + working_directory="/remote/work", + **{argument: upstream}, ) _, job = manager.rest_client.submit.call_args.args assert job["dependency"] == (f"{kind}:123:456" if multiple else f"{kind}:123") @@ -449,7 +475,7 @@ def test_dependency_futures_use_scheduler_job_ids(manager, argument, kind, multi def test_raw_dependency_requests_cancellation_if_it_can_never_be_satisfied(manager): manager.submit_job( - "examples/print_for_10s.sh", + script_path="examples/print_for_10s.sh", working_directory="/remote/work", job_options=JobOptions(dependency="afterok:123,afterany:456"), ) @@ -464,7 +490,7 @@ def test_dependency_futures_reject_a_raw_dependency(manager, argument): manager.rest_client.submit.reset_mock() with pytest.raises(ValueError, match=f"either {argument} or job_options.dependency"): manager.submit_job( - "examples/print_for_10s.sh", + script_path="examples/print_for_10s.sh", working_directory="/remote/work", job_options=JobOptions(dependency="afterany:123"), **{argument: upstream}, @@ -481,7 +507,7 @@ def test_dependencies_require_futures_from_this_manager(manager, argument): for upstream in (foreign_job, [issued, copied_job], []): with pytest.raises(ValueError, match="futures returned by this manager"): manager.submit_job( - "examples/print_for_10s.sh", + script_path="examples/print_for_10s.sh", working_directory="/remote/work", **{argument: upstream}, ) @@ -495,7 +521,7 @@ def test_dependencies_accept_completed_futures_from_this_manager(manager): assert manager._job_tracker.get_future(upstream._job_id) is None manager.submit_job( - "examples/print_for_10s.sh", working_directory="/remote/work", after_ok=upstream + script_path="examples/print_for_10s.sh", working_directory="/remote/work", after_ok=upstream ) _, job = manager.rest_client.submit.call_args.args assert job["dependency"] == "afterok:123" @@ -508,7 +534,7 @@ def test_combines_after_ok_and_after_any(manager): prepare, calibrate, monitor = (submit(manager) for _ in range(3)) manager.submit_job( - "examples/print_for_10s.sh", + script_path="examples/print_for_10s.sh", working_directory="/remote/work", after_ok=[prepare, calibrate], after_any=monitor, @@ -539,7 +565,9 @@ def test_cancellation_failure_keeps_monitoring(manager): def test_relative_remote_paths_are_rejected_before_submission(manager): with pytest.raises(ValueError, match="absolute"): - manager.submit_job("workload.sh", "activate.sh", working_directory="relative") + manager.submit_job( + script_path="workload.sh", env_path="activate.sh", working_directory="relative" + ) manager.rest_client.submit.assert_not_called() @@ -555,7 +583,7 @@ def test_public_callbacks_are_ready_before_release(manager): manager.rest_client.release.side_effect = release manager.submit_job( - "examples/print_for_10s.sh", + script_path="examples/print_for_10s.sh", working_directory="/remote/work", callbacks={"log": lambda _: received.set()}, ) @@ -733,7 +761,7 @@ def test_cluster_redis_transport_reaches_subscriber_and_worker(tmp_path, monkeyp expected.update(ssl=True, ssl_cert_reqs="required", ssl_check_hostname=True) ctor.assert_called_once_with(**expected) with mock.patch.object(manager._job_tracker, "wait_until_ready"): - manager.submit_job(workload, working_directory="/remote/work") + manager.submit_job(script_path=workload, working_directory="/remote/work") script = rest.submit.call_args.args[0] assert "--redis-address redis.example:6380" in script assert f"--redis-tls={str(tls).lower()}" in script @@ -800,7 +828,7 @@ def test_factory_binds_endpoint_credentials_and_partition_validation( with mock.patch.object(client, "submit") as submit_rest: with pytest.raises(ValidationError, match="partition"): manager.submit_job( - "examples/print_for_10s.sh", + script_path="examples/print_for_10s.sh", working_directory="/remote/work", job_options=invalid_options, ) diff --git a/test/test_slurm_rest_client.py b/test/test_slurm_rest_client.py index daf78e9..a29ed1b 100644 --- a/test/test_slurm_rest_client.py +++ b/test/test_slurm_rest_client.py @@ -198,7 +198,9 @@ def test_manager_submission_and_completion_over_http(endpoint): with mock.patch("slurm_manager.slurm_manager.RedisSubClient", return_value=redis): manager = SlurmManager(env_file=env_file) try: - future = manager.submit_job("examples/print_for_10s.sh", working_directory="/remote/work") + future = manager.submit_job( + script_path="examples/print_for_10s.sh", working_directory="/remote/work" + ) assert calls[0][3]["job"]["hold"] is True assert calls[1][3] == {"hold": False} topics = TopicInfo(future._job_id) diff --git a/worker/cmd/bec-slurm-worker/main.go b/worker/cmd/bec-slurm-worker/main.go index 6f1d2ce..0611988 100644 --- a/worker/cmd/bec-slurm-worker/main.go +++ b/worker/cmd/bec-slurm-worker/main.go @@ -1,4 +1,4 @@ -// bec-slurm-worker executes one uploaded Bash workload and forwards feedback to Redis. +// bec-slurm-worker executes one Bash workload and forwards feedback to Redis. package main import ( @@ -20,6 +20,7 @@ func main() { redisTLS := flag.Bool("redis-tls", true, "Use TLS with certificate and hostname verification") heartbeat := flag.Duration("heartbeat", time.Second, "Heartbeat interval") grace := flag.Duration("grace", 5*time.Second, "Time to terminate workload before killing it") + runCommand := flag.Bool("command", false, "Execute the payload as Bash command text") flag.Parse() if *heartbeat <= 0 || *grace <= 0 || flag.NArg() != 0 { fmt.Fprintln(os.Stderr, "Positive timing values are required; payload is JSON on stdin") @@ -39,7 +40,7 @@ func main() { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT) code, err := worker.Run(ctx, worker.Config{ JobID: payload.JobID, HeartbeatInterval: *heartbeat, GracePeriod: *grace, - Stdout: os.Stdout, Stderr: os.Stderr, + Stdout: os.Stdout, Stderr: os.Stderr, RunCommand: *runCommand, }, payload, publisher) stop() _ = publisher.Close() diff --git a/worker/internal/worker/worker.go b/worker/internal/worker/worker.go index 674d2cc..56c9757 100644 --- a/worker/internal/worker/worker.go +++ b/worker/internal/worker/worker.go @@ -23,7 +23,7 @@ import ( "github.com/redis/go-redis/v9" ) -// Payload carries the job identity and user scripts over stdin, never the submitter's credentials. +// Payload carries the job identity, Bash workload, and activation text over stdin. type Payload struct { JobID string `json:"job_id"` Script string `json:"script"` @@ -38,6 +38,7 @@ type Config struct { GracePeriod time.Duration Stdout io.Writer Stderr io.Writer + RunCommand bool } // Publisher sends a parsed message to one job topic. Implementations must bound @@ -75,6 +76,8 @@ func (p *RedisPublisher) Publish(ctx context.Context, topic string, message map[ } const shellSetup = ` +readonly bec_slurm_activation_path="$1" +readonly -a bec_slurm_workload_args=("${@:2}") if ! type module >/dev/null 2>&1; then for module_init in /etc/profile.d/modules.sh /usr/share/Modules/init/bash; do if [ -r "$module_init" ]; then @@ -83,11 +86,13 @@ if ! type module >/dev/null 2>&1; then fi done fi -source "$1" || exit $? -exec /bin/bash "$2" +if [ -n "$bec_slurm_activation_path" ]; then + source "$bec_slurm_activation_path" || exit $? +fi +exec /bin/bash "${bec_slurm_workload_args[@]}" ` -// Run stages payload scripts privately, sources activation, and executes one workload. +// Run stages activation and any uploaded script privately, then executes one Bash workload. // Config supplies the job identity, timing, and archive writers; publisher receives // log, heartbeat, and terminal messages. Cancelling ctx terminates the process group. // The returned code is the workload exit status, 143 for cancellation, or 1 for a @@ -102,18 +107,27 @@ func Run(ctx context.Context, config Config, payload Payload, publisher Publishe if config.Stderr == nil { config.Stderr = io.Discard } - directory, err := os.MkdirTemp("", "bec-slurm-worker-") - if err != nil { - return 1, err - } - defer os.RemoveAll(directory) - activation := filepath.Join(directory, "activate.sh") - script := filepath.Join(directory, "workload.sh") - if err := os.WriteFile(activation, []byte(payload.Activation), 0600); err != nil { - return 1, err - } - if err := os.WriteFile(script, []byte(payload.Script), 0600); err != nil { - return 1, err + activation, script := "", "" + + // Stage activation and script files in a temporary directory. + if payload.Activation != "" || !config.RunCommand { + directory, err := os.MkdirTemp("", "bec-slurm-worker-") + if err != nil { + return 1, err + } + defer os.RemoveAll(directory) + if payload.Activation != "" { + activation = filepath.Join(directory, "activate.sh") + if err := os.WriteFile(activation, []byte(payload.Activation), 0600); err != nil { + return 1, err + } + } + if !config.RunCommand { + script = filepath.Join(directory, "workload.sh") + if err := os.WriteFile(script, []byte(payload.Script), 0600); err != nil { + return 1, err + } + } } home, err := resolveHome() if err != nil { @@ -164,7 +178,13 @@ func Run(ctx context.Context, config Config, payload Payload, publisher Publishe stdout := &lineWriter{local: config.Stdout, stream: "stdout", publish: publish, onError: cancelWork} stderr := &lineWriter{local: config.Stderr, stream: "stderr", publish: publish, onError: cancelWork} - command := exec.Command("/bin/bash", "-c", shellSetup, "bec-slurm-worker", activation, script) + shellArgs := []string{"-c", shellSetup, "bec-slurm-worker", activation} + if config.RunCommand { + shellArgs = append(shellArgs, "-c", payload.Script, "bec-slurm-worker") + } else { + shellArgs = append(shellArgs, "--", script) + } + command := exec.Command("/bin/bash", shellArgs...) command.Env = append(os.Environ(), "HOME="+home, "SLURM_WORKER_JOBID="+config.JobID) command.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} command.Stdout, command.Stderr = stdout, stderr diff --git a/worker/internal/worker/worker_test.go b/worker/internal/worker/worker_test.go index 296ea9e..b8f46cd 100644 --- a/worker/internal/worker/worker_test.go +++ b/worker/internal/worker/worker_test.go @@ -99,6 +99,28 @@ func TestScriptsOutputAndCleanup(t *testing.T) { }) } } +func TestCommandRunsWithoutStagingWorkload(t *testing.T) { + temp := t.TempDir() + t.Setenv("TMPDIR", temp) + var out, errout bytes.Buffer + cfg := config(&out, &errout) + cfg.RunCommand = true + publisher := &fakePublisher{} + payload := Payload{ + Script: `test -z "$(find "$TMPDIR" -name workload.sh)" || exit 91 +printf '%s' "$TEST_VALUE" +exit 7`, + Activation: "export TEST_VALUE='from activation'\nset -- unused\n", + } + code, err := Run(context.Background(), cfg, payload, publisher) + if code != 7 || err == nil || out.String() != "from activation" { + t.Fatalf("exit=%d err=%v stdout=%q stderr=%q", code, err, out.String(), errout.String()) + } + if status := lastStatus(t, publisher); !strings.HasPrefix(status, "error:") { + t.Fatalf("status=%q", status) + } +} + func TestJobIDEnvironment(t *testing.T) { // An inherited value must not override this job's identity. t.Setenv("SLURM_WORKER_JOBID", "previous-job")