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, sendmsg,
recvmsg recvmsg
proc asyncExecCmd*(command: string): Future[int] = proc asyncExecCmd*(command: string): Future[string] =
let event = newAsyncEvent() let successEvent = newAsyncEvent()
let future = newFuture[int]("asyncExecCmd") let failureEvent = newAsyncEvent()
proc execCmdBackground(event: AsyncEvent, command: string): int = let future = newFuture[result.T]("asyncExecCmd")
result = execCmd(command) proc execCmdBackground(successEvent: AsyncEvent, failureEvent: AsyncEvent,
event.trigger() command: string): string =
let flowVar = spawn execCmdBackground(event, command) var exitCode: int
proc callback(fd: AsyncFD): bool = (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) future.complete(^flowVar)
true true
addEvent(event, callback) proc failureCallback(fd: AsyncFD): bool =
future.fail(newException(OSError, ^flowVar))
true
addEvent(successEvent, successCallback)
addEvent(failureEvent, failureCallback)
return future return future
type ControlMessage* = object type ControlMessage* = object

View File

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