make asyncExecCmd return the console output and raise an exception if exitcode != 0

This commit is contained in:
Christian Ulrich 2020-07-21 22:56:06 +02:00
parent 9ad26a76d9
commit 02a96ac412
No known key found for this signature in database
GPG Key ID: 8241BE099775A097
2 changed files with 28 additions and 14 deletions

View File

@ -23,17 +23,29 @@ from posix import
sendmsg,
recvmsg
proc asyncExecCmd*(command: string): Future[int] =
let event = newAsyncEvent()
let future = newFuture[int]("asyncExecCmd")
proc execCmdBackground(event: AsyncEvent, command: string): int =
result = execCmd(command)
event.trigger()
let flowVar = spawn execCmdBackground(event, command)
proc callback(fd: AsyncFD): bool =
proc asyncExecCmd*(command: string): Future[string] =
let successEvent = newAsyncEvent()
let failureEvent = newAsyncEvent()
let future = newFuture[result.T]("asyncExecCmd")
proc execCmdBackground(successEvent: AsyncEvent, failureEvent: AsyncEvent,
command: string): string =
var exitCode: int
(result, exitCode) = execCmdEx(command)
if exitCode != 0:
failureEvent.trigger()
successEvent.close() # FIXME: is close the right way to cancel an event?
else:
successEvent.trigger()
failureEvent.close() # FIXME: is close the right way to cancel an event?
let flowVar = spawn execCmdBackground(successEvent, failureEvent, command)
proc successCallback(fd: AsyncFD): bool =
future.complete(^flowVar)
true
addEvent(event, callback)
proc failureCallback(fd: AsyncFD): bool =
future.fail(newException(OSError, ^flowVar))
true
addEvent(successEvent, successCallback)
addEvent(failureEvent, failureCallback)
return future
type ControlMessage* = object

View File

@ -35,8 +35,9 @@ proc addFirewallRule(srcIp: IpAddress, srcPort: Port,
--ctorigdst {dstIp} \
--ctorigdstport {dstPort.int} \
-j DROP"""
let exitcode = await asyncExecCmd(firewall_cmd)
if exitcode != 0:
try:
discard await asyncExecCmd(firewall_cmd)
except OSError:
raise newException(PunchHoleError, "cannot add firewall rule")
proc delFirewallRule(srcIp: IpAddress, srcPort: Port,
@ -53,8 +54,9 @@ proc delFirewallRule(srcIp: IpAddress, srcPort: Port,
--ctorigdst {dstIp} \
--ctorigdstport {dstPort.int} \
-j DROP"""
let exitcode = await asyncExecCmd(firewall_cmd)
if exitcode != 0:
try:
discard await asyncExecCmd(firewall_cmd)
except OSError:
raise newException(PunchHoleError, "cannot delete firewall rule")
proc captureSeqNumbers(puncher: TcpSyniPuncher, rawFd: AsyncFD,