Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions changelog.d/+submit-sbatch-apostrophe.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
The scheduler read an apostrophe in a `#SBATCH` `--output` or
`--chdir` path as an opening quote, stopped on the unmatched quote
and never submitted the job. `eb-local submit` now double-quotes
such a path.
13 changes: 12 additions & 1 deletion src/main.zig
Original file line number Diff line number Diff line change
Expand Up @@ -6233,7 +6233,9 @@ fn nodeTypes(s: config.Settings) []const config.NodeType {
fn sbatchValue(a: Allocator, v: []const u8) []const u8 {
if (std.mem.indexOfAny(u8, v, "\n\r") != null)
die("#SBATCH directive value {s} has a newline; #SBATCH directives are single lines", .{qSingleLine(a, v)});
if (std.mem.indexOfAny(u8, v, " \t\"\\") == null) return v;
// An apostrophe starts a quote in the scheduler's directive scanner,
// the same way a double quote does, even when the path has no space.
if (std.mem.indexOfAny(u8, v, " \t\"\\'") == null) return v;
var out: std.ArrayList(u8) = .empty;
out.append(a, '"') catch oom();
for (v) |ch| switch (ch) {
Expand Down Expand Up @@ -6720,6 +6722,15 @@ fn readRetainedScript(a: Allocator, path: []const u8) ![]const u8 {
return fsx.readAll(a, opened.fd, 1 << 16);
}

test "an sbatch directive value quotes an apostrophe" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
// No space, tab, double quote, or backslash: those already take the
// quoted form. An apostrophe alone still has to be quoted.
try std.testing.expectEqualStrings("\"/home/o'brien/work\"", sbatchValue(a, "/home/o'brien/work"));
}

test "a forced collision keeps both retained submit scripts" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
Expand Down
85 changes: 85 additions & 0 deletions tests/test_submit_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,61 @@
'''


def _c_isspace(ch):
return ch in " \t\n\v\f\r"


def slurm_directive_value(line):
"""Return `(flag, value)` as `sbatch` reads one `#SBATCH` option.

The scanner is `get_argument` in the scheduler's batch option parser.
Quotes group characters, a backslash escapes the next character, and
an unmatched quote is an error. The shell does not parse the line.
"""
if not line.startswith("#SBATCH"):
raise AssertionError(line)
ptr = line[len("#SBATCH"):]
i = 0
while i < len(ptr) and _c_isspace(ptr[i]):
i += 1
out = []
quoted = False
q_char = ""
escape = False
while i < len(ptr) and (quoted or not _c_isspace(ptr[i])) and ptr[i] != "\n":
ch = ptr[i]
if escape:
escape = False
elif ch == "\\":
i += 1
if i < len(ptr) and ptr[i] == " ":
out.append(" ")
i += 1
else:
escape = True
continue
elif quoted and ch == q_char:
quoted = False
i += 1
continue
elif not quoted and ch in "\"'":
quoted = True
q_char = ch
i += 1
continue
elif not quoted and ch == "#":
break
out.append(ch)
i += 1
if quoted:
raise AssertionError(f"unmatched {q_char!r} in {line}")
text = "".join(out)
flag, sep, value = text.partition("=")
if not sep:
raise AssertionError(text)
return flag, value


@unittest.skipUnless(binary.ZIG, "submit is a feature of the Zig build")
class Submit(StorageFixture):
def setUp(self):
Expand Down Expand Up @@ -401,6 +456,36 @@ def test_sbatch_directives_quote_paths_containing_spaces(self):
self.assertIn(f'#SBATCH --output="{self.prefix}/.eb-local/logs/submit-cpu-%j.out"\n', run.stdout)
self.assertIn(f'#SBATCH --chdir="{os.path.realpath(spaced_cwd)}"\n', run.stdout)

def test_sbatch_directives_quote_paths_containing_apostrophes(self):
# `sbatch` reads `#SBATCH` with its own scanner: an apostrophe
# starts a quote, and a missing closer rejects the script. The
# shell never sees the line, because it is a comment.
work = self.root / "o'brien"
work.mkdir()
prefix = self.root / "o'prefix"
run = subprocess.run(
[binary.ZIG, "submit", "--on", "cpu", "--print", "cost$'recipe.eb", "--opt=$HOME"],
cwd=work,
env=dict(self.env, SLURM_JOB_ID="", EB_LOCAL_PREFIX=str(prefix)),
text=True,
capture_output=True,
)
self.assertEqual(run.returncode, 0, run.stdout + run.stderr)
script = run.stdout[run.stdout.index("#!/bin/bash"):]
expected = {
"--chdir": os.path.realpath(work),
"--output": f"{prefix}/.eb-local/logs/submit-cpu-%j.out",
}
for line in script.splitlines():
if not line.startswith("#SBATCH --"):
continue
flag, value = slurm_directive_value(line)
if flag in expected:
self.assertEqual(value, expected.pop(flag), line)
self.assertEqual(expected, {}, script)
command = script.rstrip().splitlines()[-1]
self.assertEqual(shlex.split(command)[-2:], ["cost$'recipe.eb", "--opt=$HOME"])


if __name__ == "__main__":
unittest.main()
Loading