From 833de33f1849e5107252324641796e48bc04522f Mon Sep 17 00:00:00 2001 From: yves Date: Wed, 14 Dec 2011 00:46:12 +0100 Subject: added error handling and logging --- createAndExportDisk.py | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/createAndExportDisk.py b/createAndExportDisk.py index 01ba10b..f10a5a8 100755 --- a/createAndExportDisk.py +++ b/createAndExportDisk.py @@ -4,35 +4,51 @@ import optparse import sys import re import subprocess +import random + +def logInfo(msg): + print("\033[1;32mINFO\033[0m " + str(msg)) + +def logErr(msg): + print("\033[1;31mERROR\033[0m " + str(msg)) class ExecutionPlan: - def __init__(self, commands): + def __init__(self, commands, comment = sys.argv[0]): self.commands = commands self.executed = [] - self.logFile = open("/tmp/log","w") + self.logFile = open("/tmp/" + comment + ".log","a") + self.logFile.write("# ### Starting new run \"" + comment + "\" ### #\r\n") + self.logFile.flush() def execute_all(self): for i in range(len(self.executed),len(self.commands)): total = len(self.commands) print("[" + str(i+1) + "/" + str(total) + "]: excuting " - + self.commands[i][0],end="") + + self.commands[i][0],end="") self.execute(self.commands[i]) print("\r[" + str(i+1) + "/" + str(total) + "]: excuted " - + self.commands[i][0] + " ") + + self.commands[i][0] + " ") def execute(self, cmd): # safty anker subprocess.call(cmd) - subprocess.call(['echo','#>>>'] + cmd,stdout=self.logFile) - subprocess.call(['echo'] + cmd,stdout=self.logFile,stderr=self.logFile) + try: + subprocess.call(['echo','#>>>'] + cmd,stdout=self.logFile) + ret = subprocess.call(['echo'] + cmd, stdout=self.logFile, stderr=self.logFile) + + if ret != 0: + print() + logErr( "\"" + cmd[0] + "\" returned error code: " + str(ret) + + ". Logged to " + self.logFile.name) + sys.exit(1) + + except OSError as e: + print() + logErr("failed to execute command \"" + cmd[0] + "\". Logged to " + + self.logFile.name + ". Error was: " + str(e)) + sys.exit(1) self.executed.append(cmd) -def logInfo(msg): - print("\033[1;32mINFO\033[0m " + str(msg)) - -def logErr(msg): - print("\033[1;31mERROR\033[0m " + str(msg)) - def parseVmName(rawString): # valdiate vm-name if not re.match('^vm-[a-z]+[0-9]?(-[a-z])?$',rawString): @@ -110,7 +126,7 @@ cmds = [ ["addIscsiDisk", vmName] ] -execPlan = ExecutionPlan(cmds) +execPlan = ExecutionPlan(cmds,vmName) execPlan.execute_all() logInfo("all done. SSH to (pang|peng).spline.de an install your vm there!") -- cgit v1.2.3-1-g7c22