2022-09-15 07:33:34 +00:00
|
|
|
# Constantine
|
|
|
|
# Copyright (c) 2018-2019 Status Research & Development GmbH
|
|
|
|
# Copyright (c) 2020-Present Mamy André-Ratsimbazafy
|
|
|
|
# Licensed and distributed under either of
|
|
|
|
# * MIT license (license terms in the root directory or at http://opensource.org/licenses/MIT).
|
|
|
|
# * Apache v2 license (license terms in the root directory or at http://www.apache.org/licenses/LICENSE-2.0).
|
|
|
|
# at your option. This file may not be copied, modified, or distributed except according to those terms.
|
|
|
|
|
|
|
|
import
|
2023-04-18 20:02:23 +00:00
|
|
|
std/[os, strutils, cpuinfo, strformat, deques],
|
2022-09-15 07:33:34 +00:00
|
|
|
std/[asyncfutures, asyncdispatch],
|
|
|
|
asynctools/[asyncproc, asyncpipe, asyncsync]
|
|
|
|
|
|
|
|
# Pararun is a parallel shell command runner
|
|
|
|
# ------------------------------------------
|
2022-10-29 20:43:40 +00:00
|
|
|
# Usage: pararun <file-with-1-command-per-line> <numWorkers>
|
2022-09-15 07:33:34 +00:00
|
|
|
|
|
|
|
# AsyncSemaphore
|
|
|
|
# ----------------------------------------------------------------
|
|
|
|
|
|
|
|
type AsyncSemaphore = ref object
|
|
|
|
waiters: Deque[Future[void]]
|
|
|
|
slots, max: int
|
|
|
|
|
|
|
|
proc new(_: type AsyncSemaphore, max: int): AsyncSemaphore =
|
|
|
|
## Initialize an AsyncSemaphore that can release up to max items
|
|
|
|
AsyncSemaphore(
|
|
|
|
waiters: default(Deque[Future[void]]),
|
|
|
|
slots: max,
|
|
|
|
max: max)
|
|
|
|
|
|
|
|
proc acquire(s: AsyncSemaphore) {.async.} =
|
|
|
|
doAssert s.slots in {0..s.max}
|
|
|
|
if s.slots == 0:
|
|
|
|
let waiter = newFuture[void]("AsyncSemaphore.acquire")
|
|
|
|
s.waiters.addLast(waiter)
|
|
|
|
await waiter
|
|
|
|
s.slots -= 1
|
|
|
|
|
|
|
|
doAssert s.slots in {0..s.max}
|
|
|
|
|
|
|
|
proc release(s: AsyncSemaphore) =
|
|
|
|
doAssert s.slots in {0..s.max-1}
|
|
|
|
|
|
|
|
s.slots += 1
|
|
|
|
if s.waiters.len > 0:
|
|
|
|
let waiter = s.waiters.popFirst()
|
|
|
|
waiter.complete()
|
2023-04-18 20:02:23 +00:00
|
|
|
|
2022-09-15 07:33:34 +00:00
|
|
|
doAssert s.slots in {0..s.max}
|
|
|
|
|
|
|
|
# Task runner
|
|
|
|
# ----------------------------------------------------------------
|
|
|
|
|
|
|
|
type WorkQueue = ref object
|
|
|
|
sem: AsyncSemaphore
|
|
|
|
cmdQueue: Deque[string]
|
2023-04-18 20:02:23 +00:00
|
|
|
outputQueue: AsyncQueue[tuple[cmd: string, p: AsyncProcess, output: AsyncQueue[string]]]
|
2022-09-15 07:33:34 +00:00
|
|
|
|
2023-04-18 20:02:23 +00:00
|
|
|
proc monitorProcessLoop(output: AsyncQueue[string], cmd: string, id, total: int, p: AsyncProcess, sem: AsyncSemaphore) {.async.} =
|
|
|
|
# Ideally we want AsynStreams but that requires chronos, which doesn't support processes/pipes
|
|
|
|
# Or the nimboost package that hasn't been updated since 2019. So poor man's streams.
|
|
|
|
template doBuffering: untyped =
|
|
|
|
while true:
|
|
|
|
buf.setLen(256)
|
|
|
|
let charsRead = await p.outputHandle.readInto(buf[0].addr, buf.len)
|
|
|
|
if charsRead > 0:
|
|
|
|
buf.setLen(charsRead)
|
|
|
|
output.putNoWait(buf)
|
|
|
|
else:
|
|
|
|
break
|
|
|
|
|
|
|
|
var buf = newString(256)
|
|
|
|
doBuffering()
|
2022-09-15 07:33:34 +00:00
|
|
|
|
2023-04-18 20:02:23 +00:00
|
|
|
# Despite the output being empty we might still get STILL_ACTIVE: https://github.com/cheatfate/asynctools/blob/84ced6d/asynctools/asyncproc.nim#L24
|
|
|
|
# Unfortunately this gives "Resource temporarily unavailable" so we use exponential backoff.
|
|
|
|
# See also:
|
|
|
|
# - https://github.com/cheatfate/asynctools/issues/20
|
|
|
|
# - https://forum.nim-lang.org/t/5565
|
|
|
|
#
|
|
|
|
# let exitCode = await p.waitForExit()
|
2022-09-18 21:37:35 +00:00
|
|
|
var backoff = 8
|
2022-09-15 07:33:34 +00:00
|
|
|
while p.running():
|
2022-09-18 21:37:35 +00:00
|
|
|
backoff = min(backoff*2, 1024) # Exponential backoff
|
|
|
|
await sleepAsync(backoff)
|
2023-04-18 20:02:23 +00:00
|
|
|
|
|
|
|
doBuffering()
|
|
|
|
buf.setLen(0)
|
|
|
|
|
|
|
|
let exitCode = p.peekExitCode()
|
|
|
|
if exitCode != 0:
|
|
|
|
buf.add("\n" & '='.repeat(26) & " Command exited with code " & $exitCode & " " & '='.repeat(26) & '\n')
|
|
|
|
buf.add("[FAIL]: '" & cmd & "' (#" & $id & "/" & $total & ")\n")
|
|
|
|
buf.add("[FAIL]: Command #" & $id & " exited with error " & $exitCode & '\n')
|
|
|
|
buf.add('='.repeat(80) & '\n')
|
|
|
|
output.putNoWait(buf)
|
|
|
|
|
|
|
|
# close not exported: https://github.com/cheatfate/asynctools/issues/16
|
|
|
|
p.inputHandle.close()
|
|
|
|
p.outputHandle.close()
|
|
|
|
p.errorHandle.close()
|
|
|
|
|
|
|
|
output.putNoWait("")
|
|
|
|
if exitCode == 0:
|
|
|
|
sem.release()
|
2022-09-15 07:33:34 +00:00
|
|
|
|
|
|
|
proc enqueuePendingCommands(wq: WorkQueue) {.async.} =
|
2023-04-18 20:02:23 +00:00
|
|
|
var id = 0
|
|
|
|
let total = wq.cmdQueue.len
|
2022-09-15 07:33:34 +00:00
|
|
|
while wq.cmdQueue.len > 0:
|
2023-04-18 20:02:23 +00:00
|
|
|
id += 1
|
|
|
|
|
2022-09-15 07:33:34 +00:00
|
|
|
await wq.sem.acquire()
|
|
|
|
let cmd = wq.cmdQueue.popFirst()
|
2023-04-18 20:02:23 +00:00
|
|
|
let p = cmd.startProcess(options = {poStdErrToStdOut, poUsePath, poEvalCommand})
|
|
|
|
|
|
|
|
let bufOut = newAsyncQueue[string]()
|
|
|
|
asyncCheck bufOut.monitorProcessLoop(cmd, id, total, p, wq.sem)
|
2022-09-15 07:33:34 +00:00
|
|
|
|
2023-04-18 20:02:23 +00:00
|
|
|
wq.outputQueue.putNoWait((cmd, p, bufOut))
|
2022-09-15 07:33:34 +00:00
|
|
|
|
2023-04-18 20:02:23 +00:00
|
|
|
proc flushCommandsOutput(wq: WorkQueue, total: int) {.async.} =
|
2022-09-18 22:41:37 +00:00
|
|
|
var id = 0
|
2022-09-15 07:33:34 +00:00
|
|
|
while true:
|
2023-04-18 20:02:23 +00:00
|
|
|
id += 1
|
|
|
|
let (cmd, p, processOutput) = await wq.outputQueue.get()
|
|
|
|
|
2022-09-15 07:33:34 +00:00
|
|
|
echo '\n', '='.repeat(80)
|
2023-04-18 20:02:23 +00:00
|
|
|
echo "||\n|| Running #", id, "/", total, ": ", cmd ,"\n||"
|
2022-09-15 07:33:34 +00:00
|
|
|
echo '='.repeat(80)
|
2023-04-18 20:02:23 +00:00
|
|
|
|
2022-09-15 07:33:34 +00:00
|
|
|
while true:
|
2023-04-18 20:02:23 +00:00
|
|
|
let output = await processOutput.get()
|
|
|
|
if output == "":
|
2022-09-15 07:33:34 +00:00
|
|
|
break
|
2023-04-18 20:02:23 +00:00
|
|
|
stdout.write(output)
|
2022-09-18 23:47:18 +00:00
|
|
|
|
2023-04-18 20:02:23 +00:00
|
|
|
let exitCode = p.peekExitCode()
|
|
|
|
if exitCode != 0:
|
|
|
|
quit exitCode
|
2022-09-15 07:33:34 +00:00
|
|
|
|
|
|
|
if wq.cmdQueue.len == 0 and wq.outputQueue.len == 0:
|
|
|
|
return
|
|
|
|
|
|
|
|
proc runCommands(commandFile: string, numWorkers: int) =
|
|
|
|
# State
|
|
|
|
# -----
|
|
|
|
|
|
|
|
let wq = WorkQueue(
|
|
|
|
sem: AsyncSemaphore.new(numWorkers),
|
|
|
|
cmdQueue: initDeque[string](),
|
2023-04-18 20:02:23 +00:00
|
|
|
outputQueue: newAsyncQueue[tuple[cmd: string, p: AsyncProcess, output: AsyncQueue[string]]]())
|
2022-09-15 07:33:34 +00:00
|
|
|
|
|
|
|
# Parse the file
|
|
|
|
# --------------
|
|
|
|
for cmd in lines(commandFile):
|
|
|
|
if cmd.len == 0: continue
|
|
|
|
wq.cmdQueue.addLast(cmd)
|
|
|
|
|
2023-04-18 20:02:23 +00:00
|
|
|
let total = wq.cmdQueue.len
|
|
|
|
echo "Found ", total, " commands to run"
|
|
|
|
|
2022-09-15 07:33:34 +00:00
|
|
|
# Run the commands
|
|
|
|
# ----------------
|
|
|
|
asyncCheck wq.enqueuePendingCommands()
|
2023-04-18 20:02:23 +00:00
|
|
|
waitFor wq.flushCommandsOutput(total)
|
2022-09-15 07:33:34 +00:00
|
|
|
|
|
|
|
# Main
|
|
|
|
# ----------------------------------------------------------------
|
2023-04-18 20:02:23 +00:00
|
|
|
|
2022-09-15 07:33:34 +00:00
|
|
|
proc main() =
|
|
|
|
var commandFile: string
|
|
|
|
var numWorkers = countProcessors()
|
|
|
|
|
|
|
|
if paramCount() == 0:
|
|
|
|
let exeName = getAppFilename().extractFilename()
|
|
|
|
echo &"Usage: {exeName} <file-with-commands-1-per-line> <numWorkers: {numWorkers}>"
|
|
|
|
|
|
|
|
if paramCount() >= 1:
|
|
|
|
commandFile = paramStr(1)
|
2023-04-18 20:02:23 +00:00
|
|
|
|
2022-09-15 07:33:34 +00:00
|
|
|
if paramCount() == 2:
|
|
|
|
numWorkers = paramStr(2).parseInt()
|
|
|
|
|
|
|
|
if paramCount() > 2:
|
|
|
|
let exeName = getAppFilename().extractFilename()
|
|
|
|
echo &"Usage: {exeName} <file-with-commands-1-per-line> <numThreads: {numWorkers}>"
|
|
|
|
quit 1
|
|
|
|
|
|
|
|
runCommands(commandFile, numWorkers)
|
|
|
|
|
|
|
|
when isMainModule:
|
|
|
|
main()
|