From 823183653570d707e4e28b19728bd4fdcb22c961 Mon Sep 17 00:00:00 2001 From: Lukas Burk Date: Thu, 3 Dec 2026 01:11:16 +0100 Subject: [PATCH 1/2] feat: optionally capture stderr separately in runOSCommand() --- NEWS.md | 1 + R/runOSCommand.R | 30 +++++++++++++++++++++++++----- man/runOSCommand.Rd | 15 ++++++++++++++- tests/testthat/test_runOSCommand.R | 30 +++++++++++++++++++++++++++--- 4 files changed, 67 insertions(+), 9 deletions(-) diff --git a/NEWS.md b/NEWS.md index 5be4e2d7..39f1f6df 100644 --- a/NEWS.md +++ b/NEWS.md @@ -6,6 +6,7 @@ * Fixed documentation regarding `store.job.collection` behavior in `makeClusterFunctions()` (#333, @n3orma) * Fixed `reduceResults()` passing the wrong `job` to `fun` when `init` is omitted: result `i + 1` was paired with job `i` (#336, @chenyangsu). * Fixed `Worker` (used by `makeClusterFunctionsSSH()`) failing on registry paths containing spaces. +* `runOSCommand()` gains arguments `stdout` and `stderr`, passed to `system2()`. With `stderr = NA`, standard error is returned separately as element `stderr` instead of being merged into `output`. The defaults keep the previous behavior (#331, @HenrikBengtsson). # batchtools 0.9.18 diff --git a/R/runOSCommand.R b/R/runOSCommand.R index 226b8458..d3de22db 100644 --- a/R/runOSCommand.R +++ b/R/runOSCommand.R @@ -11,10 +11,19 @@ #' Arguments for \code{sys.cmd}. #' @param stdin [\code{character(1)}]\cr #' Argument passed to \code{\link[base]{system2}}. +#' @param stdout [\code{logical(1)} | \code{character(1)}]\cr +#' Argument passed to \code{\link[base]{system2}}. +#' The default \code{TRUE} captures standard output in \dQuote{output}. +#' @param stderr [\code{logical(1)} | \code{character(1)}]\cr +#' Argument passed to \code{\link[base]{system2}}. +#' The default \code{TRUE} merges standard error into \dQuote{output}. +#' Set to \code{NA} to capture standard error separately in \dQuote{stderr}, so that +#' informational messages of the scheduler do not end up in the output to parse. #' @param nodename [\code{character(1)}]\cr #' Name of the SSH node to run the command on. If set to \dQuote{localhost} (default), the command #' is not piped through SSH. -#' @return [\code{named list}] with \dQuote{sys.cmd}, \dQuote{sys.args}, \dQuote{exit.code} (integer), \dQuote{output} (character). +#' @return [\code{named list}] with \dQuote{sys.cmd}, \dQuote{sys.args}, \dQuote{exit.code} (integer), \dQuote{output} (character) +#' and \dQuote{stderr} (character, \code{NULL} unless \code{stderr = NA}). #' @export #' @family ClusterFunctionsHelper #' @examples @@ -23,9 +32,11 @@ #' runOSCommand("ls", "-al") #' runOSCommand("notfound") #' } -runOSCommand = function(sys.cmd, sys.args = character(0L), stdin = "", nodename = "localhost") { +runOSCommand = function(sys.cmd, sys.args = character(0L), stdin = "", stdout = TRUE, stderr = TRUE, nodename = "localhost") { assertCharacter(sys.cmd, any.missing = FALSE, len = 1L) assertCharacter(sys.args, any.missing = FALSE) + assert(checkFlag(stdout), checkString(stdout)) + assert(checkFlag(stderr, na.ok = TRUE), checkString(stderr)) assertString(nodename, min.chars = 1L) if (!isLocalHost(nodename)) { @@ -39,10 +50,18 @@ runOSCommand = function(sys.cmd, sys.args = character(0L), stdin = "", nodename "!DEBUG [runOSCommand]: cmd: `sys.cmd` `stri_flatten(sys.args, ' ')`" + output.stderr = NULL if (nzchar(Sys.which(sys.cmd))) { - res = suppressWarnings(system2(command = sys.cmd, args = sys.args, stdin = stdin, stdout = TRUE, stderr = TRUE, wait = TRUE)) + capture.stderr = identical(stderr, NA) + if (capture.stderr) { + stderr = fs::file_temp() + on.exit(fs::file_delete(stderr[fs::file_exists(stderr)])) + } + res = suppressWarnings(system2(command = sys.cmd, args = sys.args, stdin = stdin, stdout = stdout, stderr = stderr, wait = TRUE)) output = as.character(res) exit.code = attr(res, "status") %??% 0L + if (capture.stderr) + output.stderr = if (fs::file_exists(stderr)) readLines(stderr, warn = FALSE) else character(0L) } else { output = "command not found" exit.code = 127L @@ -50,8 +69,9 @@ runOSCommand = function(sys.cmd, sys.args = character(0L), stdin = "", nodename "!DEBUG [runOSCommand]: OS result (stdin '`stdin`', exit code `exit.code`):" "!DEBUG [runOSCommand]: `paste0(output, sep = '\n')`" + "!DEBUG [runOSCommand]: stderr: `paste0(output.stderr, sep = '\n')`" - return(list(sys.cmd = sys.cmd, sys.args = sys.args, exit.code = exit.code, output = output)) + return(list(sys.cmd = sys.cmd, sys.args = sys.args, exit.code = exit.code, output = output, stderr = output.stderr)) } isLocalHost = function(nodename) { @@ -61,7 +81,7 @@ isLocalHost = function(nodename) { OSError = function(msg, res) { cmd = stri_flatten(c(res$sys.cmd, res$sys.args), collapse = " ") %??% NA_character_ exit.code = res$exit.code %??% NA_integer_ - output = stri_flatten(res$output, "\n") %??% "" + output = stri_flatten(c(res$output, res$stderr), "\n") %??% "" stopf("%s (exit code %i);\ncmd: '%s'\noutput:\n%s", msg, exit.code, cmd, output) } diff --git a/man/runOSCommand.Rd b/man/runOSCommand.Rd index 9d8b271a..d0f4e28d 100644 --- a/man/runOSCommand.Rd +++ b/man/runOSCommand.Rd @@ -8,6 +8,8 @@ runOSCommand( sys.cmd, sys.args = character(0L), stdin = "", + stdout = TRUE, + stderr = TRUE, nodename = "localhost" ) } @@ -21,12 +23,23 @@ Arguments for \code{sys.cmd}.} \item{stdin}{[\code{character(1)}]\cr Argument passed to \code{\link[base]{system2}}.} +\item{stdout}{[\code{logical(1)} | \code{character(1)}]\cr +Argument passed to \code{\link[base]{system2}}. +The default \code{TRUE} captures standard output in \dQuote{output}.} + +\item{stderr}{[\code{logical(1)} | \code{character(1)}]\cr +Argument passed to \code{\link[base]{system2}}. +The default \code{TRUE} merges standard error into \dQuote{output}. +Set to \code{NA} to capture standard error separately in \dQuote{stderr}, so that +informational messages of the scheduler do not end up in the output to parse.} + \item{nodename}{[\code{character(1)}]\cr Name of the SSH node to run the command on. If set to \dQuote{localhost} (default), the command is not piped through SSH.} } \value{ -[\code{named list}] with \dQuote{sys.cmd}, \dQuote{sys.args}, \dQuote{exit.code} (integer), \dQuote{output} (character). +[\code{named list}] with \dQuote{sys.cmd}, \dQuote{sys.args}, \dQuote{exit.code} (integer), \dQuote{output} (character) + and \dQuote{stderr} (character, \code{NULL} unless \code{stderr = NA}). } \description{ This is a helper function to run arbitrary OS commands on local or remote machines. diff --git a/tests/testthat/test_runOSCommand.R b/tests/testthat/test_runOSCommand.R index cfc0a25c..4daa6d56 100644 --- a/tests/testthat/test_runOSCommand.R +++ b/tests/testthat/test_runOSCommand.R @@ -1,8 +1,9 @@ test_that("runOSCommand", { skip_on_os(c("windows", "solaris")) # system2 is broken on solaris x = runOSCommand("ls", find.package("batchtools")) - expect_list(x, names = "named", len = 4L) - expect_names(names(x), permutation.of = c("sys.cmd", "sys.args", "exit.code", "output")) + expect_list(x, names = "named", len = 5L) + expect_names(names(x), permutation.of = c("sys.cmd", "sys.args", "exit.code", "output", "stderr")) + expect_null(x$stderr) expect_identical(x$exit.code, 0L) expect_true(all(c("DESCRIPTION", "NAMESPACE", "NEWS.md") %chin% x$output)) }) @@ -10,7 +11,7 @@ test_that("runOSCommand", { test_that("command not found", { skip_on_os("solaris") # system2 is broken on solaris res = runOSCommand("notfoundcommand") - expect_list(res, len = 4) + expect_list(res, len = 5) expect_identical(res$exit.code, 127L) expect_identical(res$output, "command not found") expect_error(OSError("Command not found", res), pattern = "Command not found") @@ -29,3 +30,26 @@ test_that("stdin", { expect_identical(res$output, letters) fs::file_delete(tf) }) + +test_that("stderr is merged by default and separated with stderr = NA", { + skip_on_os(c("windows", "solaris")) # system2 is broken on solaris + args = c("-c", shQuote("echo info >&2; echo answer")) + + res = runOSCommand("sh", args) + expect_set_equal(res$output, c("info", "answer")) + expect_null(res$stderr) + + res = runOSCommand("sh", args, stderr = NA) + expect_identical(res$output, "answer") + expect_identical(res$stderr, "info") + + res = runOSCommand("sh", c("-c", shQuote("echo answer")), stderr = NA) + expect_identical(res$stderr, character(0L)) +}) + +test_that("OSError reports separated stderr", { + skip_on_os(c("windows", "solaris")) # system2 is broken on solaris + res = runOSCommand("sh", c("-c", shQuote("echo broken >&2; exit 3")), stderr = NA) + expect_identical(res$exit.code, 3L) + expect_error(OSError("Failed", res), "broken") +}) From 06a8217a88046e51b5d648aab00ee3e2b202e455 Mon Sep 17 00:00:00 2001 From: Lukas Burk Date: Thu, 3 Dec 2026 01:11:17 +0100 Subject: [PATCH 2/2] fix: parse Slurm and LSF batch ids from stdout only --- NEWS.md | 2 ++ R/clusterFunctionsLSF.R | 13 +++++++++---- R/clusterFunctionsSlurm.R | 16 ++++++++++++---- tests/testthat/test_parseBatchId.R | 18 ++++++++++++++++++ 4 files changed, 41 insertions(+), 8 deletions(-) create mode 100644 tests/testthat/test_parseBatchId.R diff --git a/NEWS.md b/NEWS.md index 39f1f6df..ce345cf3 100644 --- a/NEWS.md +++ b/NEWS.md @@ -7,6 +7,8 @@ * Fixed `reduceResults()` passing the wrong `job` to `fun` when `init` is omitted: result `i + 1` was paired with job `i` (#336, @chenyangsu). * Fixed `Worker` (used by `makeClusterFunctionsSSH()`) failing on registry paths containing spaces. * `runOSCommand()` gains arguments `stdout` and `stderr`, passed to `system2()`. With `stderr = NA`, standard error is returned separately as element `stderr` instead of being merged into `output`. The defaults keep the previous behavior (#331, @HenrikBengtsson). +* `makeClusterFunctionsSlurm()` now submits with `sbatch --parsable` and parses only stdout, so informational messages printed by `sbatch` no longer corrupt the batch id (#243, #314, @bwcompton). +* `makeClusterFunctionsLSF()` now extracts the batch id from the `Job ` part of the `bsub` output, ignoring messages on stderr (#244, @michaelmayer2). # batchtools 0.9.18 diff --git a/R/clusterFunctionsLSF.R b/R/clusterFunctionsLSF.R index c151c697..923f5325 100644 --- a/R/clusterFunctionsLSF.R +++ b/R/clusterFunctionsLSF.R @@ -38,12 +38,12 @@ makeClusterFunctionsLSF = function(template = "lsf", scheduler.latency = 1, fs.l assertRegistry(reg, writeable = TRUE) assertClass(jc, "JobCollection") outfile = cfBrewTemplate(reg, template, jc) - res = runOSCommand("bsub", stdin = outfile) + res = runOSCommand("bsub", stdin = outfile, stderr = NA) + batch.id = parseLSFBatchId(res$output) - if (res$exit.code > 0L) { - cfHandleUnknownSubmitError("bsub", res$exit.code, res$output) + if (res$exit.code > 0L || is.na(batch.id)) { + cfHandleUnknownSubmitError("bsub", res$exit.code, c(res$output, res$stderr)) } else { - batch.id = stri_extract_first_regex(stri_flatten(res$output, " "), "\\d+") makeSubmitJobResult(status = 0L, batch.id = batch.id) } } @@ -76,3 +76,8 @@ makeClusterFunctionsLSF = function(template = "lsf", scheduler.latency = 1, fs.l makeClusterFunctions(name = "LSF", submitJob = submitJob, killJob = killJob, listJobsQueued = listJobsQueued, listJobsRunning = listJobsRunning, store.job.collection = TRUE, scheduler.latency = scheduler.latency, fs.latency = fs.latency) } # nocov end + +# `bsub` prints "Job is submitted to queue ." +parseLSFBatchId = function(output) { + stri_match_first_regex(stri_flatten(output, " "), "Job <([0-9]+)>")[, 2L] +} diff --git a/R/clusterFunctionsSlurm.R b/R/clusterFunctionsSlurm.R index 56385dc8..af78d96e 100644 --- a/R/clusterFunctionsSlurm.R +++ b/R/clusterFunctionsSlurm.R @@ -51,8 +51,8 @@ makeClusterFunctionsSlurm = function(template = "slurm", array.jobs = TRUE, node jc$log.file = stri_join(jc$log.file, "_%a") } outfile = cfBrewTemplate(reg, template, jc) - res = runOSCommand("sbatch", shQuote(outfile), nodename = nodename) - output = stri_flatten(stri_trim_both(res$output), "\n") + res = runOSCommand("sbatch", c("--parsable", shQuote(outfile)), stderr = NA, nodename = nodename) + output = stri_flatten(stri_trim_both(c(res$output, res$stderr)), "\n") if (res$exit.code > 0L) { temp.errors = c( @@ -63,10 +63,12 @@ makeClusterFunctionsSlurm = function(template = "slurm", array.jobs = TRUE, node i = wf(stri_detect_fixed(output, temp.errors)) if (length(i) == 1L) return(makeSubmitJobResult(status = i, batch.id = NA_character_, msg = temp.errors[i])) - return(cfHandleUnknownSubmitError("sbatch", res$exit.code, res$output)) + return(cfHandleUnknownSubmitError("sbatch", res$exit.code, c(res$output, res$stderr))) } - id = stri_split_fixed(output[1L], " ")[[1L]][4L] + id = parseSlurmBatchId(res$output) + if (is.na(id)) + return(cfHandleUnknownSubmitError("sbatch", res$exit.code, c(res$output, res$stderr))) if (jc$array.jobs) { if (!array.jobs) stop("Array jobs not supported by cluster function") @@ -120,3 +122,9 @@ makeClusterFunctionsSlurm = function(template = "slurm", array.jobs = TRUE, node listJobsQueued = listJobsQueued, array.var = "SLURM_ARRAY_TASK_ID", store.job.collection = TRUE, store.job.files = !isLocalHost(nodename), scheduler.latency = scheduler.latency, fs.latency = fs.latency) } # nocov end + +# `sbatch --parsable` prints "" or ";" on stdout +parseSlurmBatchId = function(output) { + output = stri_trim_both(output) + stri_extract_first_regex(output[stri_detect_regex(output, "^[0-9]+(;.*)?$")][1L], "^[0-9]+") +} diff --git a/tests/testthat/test_parseBatchId.R b/tests/testthat/test_parseBatchId.R new file mode 100644 index 00000000..5f65bce4 --- /dev/null +++ b/tests/testthat/test_parseBatchId.R @@ -0,0 +1,18 @@ +test_that("parseSlurmBatchId", { + expect_identical(parseSlurmBatchId("1556425"), "1556425") + expect_identical(parseSlurmBatchId("1556425;cluster1"), "1556425") + expect_identical(parseSlurmBatchId(c("", " 42933105 ")), "42933105") + # banner lines on stdout as in #314 must not be picked up + expect_identical(parseSlurmBatchId(c("This is crazy", "and uncalled for", "5555555", "and even more stuff")), "5555555") + expect_identical(parseSlurmBatchId("Submitted batch job 1556425"), NA_character_) + expect_identical(parseSlurmBatchId(character(0L)), NA_character_) +}) + +test_that("parseLSFBatchId", { + expect_identical(parseLSFBatchId("Job <12345> is submitted to queue ."), "12345") + expect_identical(parseLSFBatchId("Job <12345> is submitted to default queue ."), "12345") + # resource defaults announced by an esub before the submit line, as in #244 + out = c("Memory limit not specified, using default of 4 GB per core.", "Wall time set to 24:00.", "Job <987654> is submitted to queue .") + expect_identical(parseLSFBatchId(out), "987654") + expect_identical(parseLSFBatchId("Request aborted by esub. Job not submitted."), NA_character_) +})