From 752736d288e356875e5a3198bf1ef1dd43ac9f34 Mon Sep 17 00:00:00 2001 From: Thierry Parmentelat Date: Tue, 28 Apr 2015 13:09:34 +0200 Subject: [PATCH] prettifying source/ comprehension instead of map --- source/BootAPI.py | 70 +++--- source/BootManager.py | 18 +- source/BootServerRequest.py | 277 ++++++++++++------------ source/Exceptions.py | 8 +- source/ModelOptions.py | 26 +-- source/RunlevelAgent.py | 40 ++-- source/configuration | 6 +- source/notify_messages.py | 22 +- source/steps/UpdateNodeConfiguration.py | 6 +- source/systeminfo.py | 107 +++++---- source/utils.py | 126 ++++++----- 11 files changed, 347 insertions(+), 359 deletions(-) diff --git a/source/BootAPI.py b/source/BootAPI.py index c7d8105..c24afbc 100644 --- a/source/BootAPI.py +++ b/source/BootAPI.py @@ -20,7 +20,7 @@ from Exceptions import * stash = None -def create_auth_structure( vars, call_params ): +def create_auth_structure(vars, call_params): """ create and return an authentication structure for a Boot API call. Vars contains the boot manager runtime variables, and @@ -29,7 +29,7 @@ def create_auth_structure( vars, call_params ): keys in vars, such as node_id or node_key) """ - auth= {} + auth = {} try: auth_session = {} @@ -52,16 +52,16 @@ def create_auth_structure( vars, call_params ): auth = auth_session except: - auth['AuthMethod']= 'hmac' + auth['AuthMethod'] = 'hmac' try: auth['node_id'] = vars['NODE_ID'] auth['node_ip'] = vars['INTERFACE_SETTINGS']['ip'] - except KeyError, e: + except KeyError as e: return None - node_hmac= hmac.new(vars['NODE_KEY'], "[]".encode('utf-8'), sha).hexdigest() - auth['value']= node_hmac + node_hmac = hmac.new(vars['NODE_KEY'], "[]".encode('utf-8'), sha).hexdigest() + auth['value'] = node_hmac try: auth_session = {} if not vars.has_key('NODE_SESSION'): @@ -73,7 +73,7 @@ def create_auth_structure( vars, call_params ): if not os.path.exists("/etc/planetlab"): os.makedirs("/etc/planetlab") sessionfile = open('/etc/planetlab/session', 'w') - sessionfile.write( vars['NODE_SESSION'] ) + sessionfile.write(vars['NODE_SESSION']) sessionfile.close() else: auth_session['session'] = vars['NODE_SESSION'] @@ -81,14 +81,14 @@ def create_auth_structure( vars, call_params ): auth_session['AuthMethod'] = 'session' auth = auth_session - except Exception, e: + except Exception as e: # NOTE: BM has failed to authenticate utterly. - raise BootManagerAuthenticationException, "%s" % e + raise BootManagerAuthenticationException("{}".format(e)) return auth -def serialize_params( call_params ): +def serialize_params(call_params): """ convert a list of parameters into a format that will be used in the hmac generation. both the boot manager and plc must have a common @@ -98,7 +98,7 @@ def serialize_params( call_params ): them into one long string encased in a set of braces. """ - values= [] + values = [] for param in call_params: if isinstance(param,list) or isinstance(param,tuple): @@ -119,7 +119,7 @@ def serialize_params( call_params ): return values -def call_api_function( vars, function, user_params ): +def call_api_function(vars, function, user_params): """ call the named api function with params, and return the value to the caller. the authentication structure is handled @@ -130,9 +130,9 @@ def call_api_function( vars, function, user_params ): global stash try: - api_server= vars['API_SERVER_INST'] - except KeyError, e: - raise BootManagerException, "No connection to the API server exists." + api_server = vars['API_SERVER_INST'] + except KeyError as e: + raise BootManagerException("No connection to the API server exists.") if api_server is None: if not stash: @@ -140,29 +140,29 @@ def call_api_function( vars, function, user_params ): for i in stash: if i[0] == function and i[1] == user_params: return i[2] - raise BootManagerException, \ - "Disconnected operation failed, insufficient stash." + raise BootManagerException( + "Disconnected operation failed, insufficient stash.") - auth= create_auth_structure(vars,user_params) + auth = create_auth_structure(vars,user_params) if auth is None: - raise BootManagerException, \ - "Could not create auth structure, missing values." + raise BootManagerException( + "Could not create auth structure, missing values.") - params= (auth,) - params= params + user_params + params = (auth,) + params = params + user_params try: - exec( "rc= api_server.%s(*params)" % function ) + exec("rc= api_server.{}(*params)".format(function)) if stash is None: stash = [] stash += [ [ function, user_params, rc ] ] return rc - except xmlrpclib.Fault, fault: - raise BootManagerException, "API Fault: %s" % fault - except xmlrpclib.ProtocolError, err: - raise BootManagerException,"XML RPC protocol error: %s" % err - except xml.parsers.expat.ExpatError, err: - raise BootManagerException,"XML parsing error: %s" % err + except xmlrpclib.Fault as fault: + raise BootManagerException("API Fault: {}".format(fault)) + except xmlrpclib.ProtocolError as err: + raise BootManagerException("XML RPC protocol error: {}".format(err)) + except xml.parsers.expat.ExpatError as err: + raise BootManagerException("XML parsing error: {}".format(err)) class Stash(file): @@ -170,18 +170,18 @@ class Stash(file): def __init__(self, vars, mode): utils.makedirs(self.mntpnt) try: - utils.sysexec('mount -t auto -U %s %s' % (vars['DISCONNECTED_OPERATION'], self.mntpnt)) + utils.sysexec('mount -t auto -U {} {}'.format(vars['DISCONNECTED_OPERATION'], self.mntpnt)) # make sure it's not read-only - f = file('%s/api.cache' % self.mntpnt, 'a') + f = file('{}/api.cache'.format(self.mntpnt), 'a') f.close() - file.__init__(self, '%s/api.cache' % self.mntpnt, mode) + file.__init__(self, '{}/api.cache'.format(self.mntpnt), mode) except: - utils.sysexec_noerr('umount %s' % self.mntpnt) - raise BootManagerException, "Couldn't find API-cache for disconnected operation" + utils.sysexec_noerr('umount {}'.format(self.mntpnt)) + raise BootManagerException("Couldn't find API-cache for disconnected operation") def close(self): file.close(self) - utils.sysexec_noerr('umount %s' % self.mntpnt) + utils.sysexec_noerr('umount {}'.format(self.mntpnt)) def load(vars): global stash diff --git a/source/BootManager.py b/source/BootManager.py index 2857d9d..2518fb6 100755 --- a/source/BootManager.py +++ b/source/BootManager.py @@ -23,12 +23,12 @@ BM_NODE_LOG = "/tmp/bm.log" VARS_FILE = "configuration" # the new contents of PATH when the boot manager is running -BIN_PATH= ('/usr/local/bin', - '/usr/local/sbin', - '/usr/bin', - '/usr/sbin', - '/bin', - '/sbin') +BIN_PATH = ('/usr/local/bin', + '/usr/local/sbin', + '/usr/bin', + '/usr/sbin', + '/bin', + '/sbin') def read_configuration_file(filename): # read in and store all variables in VARS_FILE into each line @@ -43,7 +43,7 @@ def read_configuration_file(filename): if line[:1] == "#" or string.strip(line) == "": continue - parts = string.split(line,"=") + parts = string.split(line, "=") if len(parts) != 2: validConfFile = False raise Exception("Invalid line in vars file: {}".format(line)) @@ -128,7 +128,7 @@ class log: self.LogEntry("Uploading logs to {}".format(self.VARS['UPLOAD_LOG_SCRIPT'])) self.OutputFile.close() - self.OutputFile= None + self.OutputFile = None hostname = self.VARS['INTERFACE_SETTINGS']['hostname'] + "." + \ self.VARS['INTERFACE_SETTINGS']['domainname'] @@ -433,6 +433,6 @@ def main(argv): return error -if __name__ == "__main__": +if __name__ ==e "__main__": error = main(sys.argv) sys.exit(error) diff --git a/source/BootServerRequest.py b/source/BootServerRequest.py index 88cd081..7b6531d 100644 --- a/source/BootServerRequest.py +++ b/source/BootServerRequest.py @@ -6,6 +6,8 @@ # Copyright (c) 2004-2006 The Trustees of Princeton University # All rights reserved. +from __future__ import print_function + import os, sys import re import string @@ -15,9 +17,9 @@ import tempfile # try to load pycurl try: import pycurl - PYCURL_LOADED= 1 + PYCURL_LOADED = 1 except: - PYCURL_LOADED= 0 + PYCURL_LOADED = 0 # if there is no cStringIO, fall back to the original @@ -35,30 +37,30 @@ class BootServerRequest: # all possible places to check the cdrom mount point. # /mnt/cdrom is typically after the machine has come up, # and /usr is when the boot cd is running - CDROM_MOUNT_PATH = ("/mnt/cdrom/","/usr/") - BOOTSERVER_CERTS= {} - MONITORSERVER_CERTS= {} - BOOTCD_VERSION="" - HTTP_SUCCESS=200 - HAS_BOOTCD=0 - USE_PROXY=0 - PROXY=0 + CDROM_MOUNT_PATH = ("/mnt/cdrom/", "/usr/") + BOOTSERVER_CERTS = {} + MONITORSERVER_CERTS = {} + BOOTCD_VERSION = "" + HTTP_SUCCESS = 200 + HAS_BOOTCD = 0 + USE_PROXY = 0 + PROXY = 0 # in seconds, how maximum time allowed for connect - DEFAULT_CURL_CONNECT_TIMEOUT=30 + DEFAULT_CURL_CONNECT_TIMEOUT = 30 # in seconds, maximum time allowed for any transfer - DEFAULT_CURL_MAX_TRANSFER_TIME=3600 + DEFAULT_CURL_MAX_TRANSFER_TIME = 3600 # location of curl executable, if pycurl isn't available # and the DownloadFile method is called (backup, only # really need for the boot cd environment where pycurl # doesn't exist CURL_CMD = 'curl' - CURL_SSL_VERSION=3 + CURL_SSL_VERSION = 3 def __init__(self, vars, verbose=0): - self.VERBOSE= verbose - self.VARS=vars + self.VERBOSE = verbose + self.VARS = vars # see if we have a boot cd mounted by checking for the version file # if HAS_BOOTCD == 0 then either the machine doesn't have @@ -66,106 +68,100 @@ class BootServerRequest: self.HAS_BOOTCD = 0 for path in self.CDROM_MOUNT_PATH: - self.Message( "Checking existance of boot cd on %s" % path ) + self.Message("Checking existance of boot cd on {}".format(path)) - os.system("/bin/mount %s > /dev/null 2>&1" % path ) + os.system("/bin/mount {} > /dev/null 2>&1".format(path)) - version_file= self.VARS['BOOTCD_VERSION_FILE'] % {'path' : path} - self.Message( "Looking for version file %s" % version_file ) + version_file = self.VARS['BOOTCD_VERSION_FILE'].format(path=path) + self.Message("Looking for version file {}".format(version_file)) if os.access(version_file, os.R_OK) == 0: - self.Message( "No boot cd found." ); + self.Message("No boot cd found."); else: - self.Message( "Found boot cd." ) - self.HAS_BOOTCD=1 + self.Message("Found boot cd.") + self.HAS_BOOTCD = 1 break if self.HAS_BOOTCD: # check the version of the boot cd, and locate the certs - self.Message( "Getting boot cd version." ) + self.Message("Getting boot cd version.") - versionRegExp= re.compile(r"PlanetLab BootCD v(\S+)") + versionRegExp = re.compile(r"PlanetLab BootCD v(\S+)") - bootcd_version_f= file(version_file,"r") - line= string.strip(bootcd_version_f.readline()) + bootcd_version_f = file(version_file, "r") + line = string.strip(bootcd_version_f.readline()) bootcd_version_f.close() - match= versionRegExp.findall(line) + match = versionRegExp.findall(line) if match: - (self.BOOTCD_VERSION)= match[0] + (self.BOOTCD_VERSION) = match[0] # right now, all the versions of the bootcd are supported, # so no need to check it - self.Message( "Getting server from configuration" ) + self.Message("Getting server from configuration") - bootservers= [ self.VARS['BOOT_SERVER'] ] + bootservers = [ self.VARS['BOOT_SERVER'] ] for bootserver in bootservers: bootserver = string.strip(bootserver) - cacert_path= "%s/%s/%s" % \ - (self.VARS['SERVER_CERT_DIR'] % {'path' : path}, - bootserver,self.VARS['CACERT_NAME']) + cacert_path = "{}/{}/{}".format( + self.VARS['SERVER_CERT_DIR'].format(path=path), + bootserver, + self.VARS['CACERT_NAME']) if os.access(cacert_path, os.R_OK): - self.BOOTSERVER_CERTS[bootserver]= cacert_path + self.BOOTSERVER_CERTS[bootserver] = cacert_path - monitorservers= [ self.VARS['MONITOR_SERVER'] ] + monitorservers = [ self.VARS['MONITOR_SERVER'] ] for monitorserver in monitorservers: monitorserver = string.strip(monitorserver) - cacert_path= "%s/%s/%s" % \ - (self.VARS['SERVER_CERT_DIR'] % {'path' : path}, - monitorserver,self.VARS['CACERT_NAME']) + cacert_path = "{}/{}/{}".format( + self.VARS['SERVER_CERT_DIR'].format(path=path), + monitorserver, + self.VARS['CACERT_NAME']) if os.access(cacert_path, os.R_OK): - self.MONITORSERVER_CERTS[monitorserver]= cacert_path + self.MONITORSERVER_CERTS[monitorserver] = cacert_path - self.Message( "Set of servers to contact: %s" % - str(self.BOOTSERVER_CERTS) ) - self.Message( "Set of servers to upload to: %s" % - str(self.MONITORSERVER_CERTS) ) + self.Message("Set of servers to contact: {}".format(self.BOOTSERVER_CERTS)) + self.Message("Set of servers to upload to: {}".format(self.MONITORSERVER_CERTS)) else: - self.Message( "Using default boot server address." ) - self.BOOTSERVER_CERTS[self.VARS['DEFAULT_BOOT_SERVER']]= "" - self.MONITORSERVER_CERTS[self.VARS['DEFAULT_BOOT_SERVER']]= "" + self.Message("Using default boot server address.") + self.BOOTSERVER_CERTS[self.VARS['DEFAULT_BOOT_SERVER']] = "" + self.MONITORSERVER_CERTS[self.VARS['DEFAULT_BOOT_SERVER']] = "" - def CheckProxy( self ): + def CheckProxy(self): # see if we have any proxy info from the machine - self.USE_PROXY= 0 - self.Message( "Checking existance of proxy config file..." ) + self.USE_PROXY = 0 + self.Message("Checking existance of proxy config file...") if os.access(self.VARS['PROXY_FILE'], os.R_OK) and \ os.path.isfile(self.VARS['PROXY_FILE']): - self.PROXY= string.strip(file(self.VARS['PROXY_FILE'],'r').readline()) - self.USE_PROXY= 1 - self.Message( "Using proxy %s." % self.PROXY) + self.PROXY = string.strip(file(self.VARS['PROXY_FILE'], 'r').readline()) + self.USE_PROXY = 1 + self.Message("Using proxy {}.".format(self.PROXY)) else: - self.Message( "Not using any proxy." ) - - - - def Message( self, Msg ): - if( self.VERBOSE ): - print( Msg ) - + self.Message("Not using any proxy.") - def Error( self, Msg ): - sys.stderr.write( Msg + "\n" ) + def Message(self, Msg): + if(self.VERBOSE): + print(Msg) + def Error(self, Msg): + sys.stderr.write(Msg + "\n") - def Warning( self, Msg ): + def Warning(self, Msg): self.Error(Msg) - - - def MakeRequest( self, PartialPath, GetVars, + def MakeRequest(self, PartialPath, GetVars, PostVars, DoSSL, DoCertCheck, - ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT, - MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME, - FormData= None): + ConnectTimeout = DEFAULT_CURL_CONNECT_TIMEOUT, + MaxTransferTime = DEFAULT_CURL_MAX_TRANSFER_TIME, + FormData = None): - (fd, buffer_name) = tempfile.mkstemp("MakeRequest-XXXXXX") + fd, buffer_name = tempfile.mkstemp("MakeRequest-XXXXXX") os.close(fd) buffer = open(buffer_name, "w+b") @@ -195,41 +191,41 @@ class BootServerRequest: def DownloadFile(self, PartialPath, GetVars, PostVars, DoSSL, DoCertCheck, DestFilePath, - ConnectTimeout= DEFAULT_CURL_CONNECT_TIMEOUT, - MaxTransferTime= DEFAULT_CURL_MAX_TRANSFER_TIME, - FormData= None): + ConnectTimeout = DEFAULT_CURL_CONNECT_TIMEOUT, + MaxTransferTime = DEFAULT_CURL_MAX_TRANSFER_TIME, + FormData = None): - self.Message( "Attempting to retrieve %s" % PartialPath ) + self.Message("Attempting to retrieve {}".format(PartialPath)) # we can't do ssl and check the cert if we don't have a bootcd if DoSSL and DoCertCheck and not self.HAS_BOOTCD: - self.Error( "No boot cd exists (needed to use -c and -s.\n" ) + self.Error("No boot cd exists (needed to use -c and -s.\n") return 0 if DoSSL and not PYCURL_LOADED: - self.Warning( "Using SSL without pycurl will by default " \ - "check at least standard certs." ) + self.Warning("Using SSL without pycurl will by default " \ + "check at least standard certs.") # ConnectTimeout has to be greater than 0 if ConnectTimeout <= 0: - self.Error( "Connect timeout must be greater than zero.\n" ) + self.Error("Connect timeout must be greater than zero.\n") return 0 self.CheckProxy() - dopostdata= 0 + dopostdata = 0 # setup the post and get vars for the request if PostVars: - dopostdata= 1 + dopostdata = 1 postdata = urllib.urlencode(PostVars) - self.Message( "Posting data:\n%s\n" % postdata ) + self.Message("Posting data:\n{}\n".format(postdata)) - getstr= "" + getstr = "" if GetVars: - getstr= "?" + urllib.urlencode(GetVars) - self.Message( "Get data:\n%s\n" % getstr ) + getstr = "?" + urllib.urlencode(GetVars) + self.Message("Get data:\n{}\n".format(getstr)) # now, attempt to make the request, starting at the first # server in the list @@ -239,37 +235,34 @@ class BootServerRequest: cert_list = self.BOOTSERVER_CERTS for server in cert_list: - self.Message( "Contacting server %s." % server ) + self.Message("Contacting server {}.".format(server)) certpath = cert_list[server] # output what we are going to be doing - self.Message( "Connect timeout is %s seconds" % \ - ConnectTimeout ) - - self.Message( "Max transfer time is %s seconds" % \ - MaxTransferTime ) + self.Message("Connect timeout is {} seconds".format(ConnectTimeout)) + self.Message("Max transfer time is {} seconds".format(MaxTransferTime)) if DoSSL: - url = "https://%s/%s%s" % (server,PartialPath,getstr) + url = "https://{}/{}{}".format(server, PartialPath, getstr) if DoCertCheck and PYCURL_LOADED: - self.Message( "Using SSL version %d and verifying peer." % - self.CURL_SSL_VERSION ) + self.Message("Using SSL version {} and verifying peer." + .format(self.CURL_SSL_VERSION)) else: - self.Message( "Using SSL version %d." % - self.CURL_SSL_VERSION ) + self.Message("Using SSL version {}." + .format(self.CURL_SSL_VERSION)) else: - url = "http://%s/%s%s" % (server,PartialPath,getstr) + url = "http://{}/{}{}".format(server, PartialPath, getstr) - self.Message( "URL: %s" % url ) + self.Message("URL: {}".format(url)) # setup a new pycurl instance, or a curl command line string # if we don't have pycurl if PYCURL_LOADED: - curl= pycurl.Curl() + curl = pycurl.Curl() # don't want curl sending any signals curl.setopt(pycurl.NOSIGNAL, 1) @@ -281,7 +274,7 @@ class BootServerRequest: curl.setopt(pycurl.FOLLOWLOCATION, 0) if self.USE_PROXY: - curl.setopt(pycurl.PROXY, self.PROXY ) + curl.setopt(pycurl.PROXY, self.PROXY) if DoSSL: curl.setopt(pycurl.SSLVERSION, self.CURL_SSL_VERSION) @@ -303,14 +296,14 @@ class BootServerRequest: curl.setopt(pycurl.URL, url) else: - cmdline = "%s " \ - "--connect-timeout %d " \ - "--max-time %d " \ + cmdline = "{} " \ + "--connect-timeout {} " \ + "--max-time {} " \ "--header Pragma: " \ - "--output %s " \ - "--fail " % \ - (self.CURL_CMD, ConnectTimeout, - MaxTransferTime, DestFilePath) + "--output {} " \ + "--fail "\ + .format(self.CURL_CMD, ConnectTimeout, + MaxTransferTime, DestFilePath) if dopostdata: cmdline = cmdline + "--data '" + postdata + "' " @@ -322,16 +315,16 @@ class BootServerRequest: cmdline = cmdline + "--silent " if self.USE_PROXY: - cmdline = cmdline + "--proxy %s " % self.PROXY + cmdline = cmdline + "--proxy {} ".format(self.PROXY) if DoSSL: - cmdline = cmdline + "--sslv%d " % self.CURL_SSL_VERSION + cmdline = cmdline + "--sslv{} ".format(self.CURL_SSL_VERSION) if DoCertCheck: - cmdline = cmdline + "--cacert %s " % certpath + cmdline = cmdline + "--cacert {} ".format(certpath) cmdline = cmdline + url - self.Message( "curl command: %s" % cmdline ) + self.Message("curl command: {}".format(cmdline)) if PYCURL_LOADED: @@ -339,32 +332,32 @@ class BootServerRequest: # setup the output file outfile = open(DestFilePath,"wb") - self.Message( "Opened output file %s" % DestFilePath ) + self.Message("Opened output file {}".format(DestFilePath)) curl.setopt(pycurl.WRITEDATA, outfile) - self.Message( "Fetching..." ) + self.Message("Fetching...") curl.perform() - self.Message( "Done." ) + self.Message("Done.") - http_result= curl.getinfo(pycurl.HTTP_CODE) + http_result = curl.getinfo(pycurl.HTTP_CODE) curl.close() outfile.close() - self.Message( "Results saved in %s" % DestFilePath ) + self.Message("Results saved in {}".format(DestFilePath)) # check the code, return 1 if successfull if http_result == self.HTTP_SUCCESS: - self.Message( "Successfull!" ) + self.Message("Successfull!") return 1 else: - self.Message( "Failure, resultant http code: %d" % \ - http_result ) + self.Message("Failure, resultant http code: {}" + .format(http_result)) - except pycurl.error, err: - errno, errstr= err - self.Error( "connect to %s failed; curl error %d: '%s'\n" % - (server,errno,errstr) ) + except pycurl.error as err: + errno, errstr = err + self.Error("connect to {} failed; curl error {}: '{}'\n" + .format(server, errno, errstr)) if not outfile.closed: try: @@ -374,22 +367,22 @@ class BootServerRequest: pass else: - self.Message( "Fetching..." ) + self.Message("Fetching...") rc = os.system(cmdline) - self.Message( "Done." ) + self.Message("Done.") if rc != 0: try: - os.unlink( DestFilePath ) + os.unlink(DestFilePath) except OSError: pass - self.Message( "Failure, resultant curl code: %d" % rc ) - self.Message( "Removed %s" % DestFilePath ) + self.Message("Failure, resultant curl code: {}".format(rc)) + self.Message("Removed {}".format(DestFilePath)) else: - self.Message( "Successfull!" ) + self.Message("Successfull!") return 1 - self.Error( "Unable to successfully contact any boot servers.\n" ) + self.Error("Unable to successfully contact any boot servers.\n") return 0 @@ -419,10 +412,10 @@ if __name__ == "__main__": [ "output=", "verbose", \ "help","ssl","checkcert"]) - ssl= 0 - checkcert= 0 - output_file= None - verbose= 0 + ssl = 0 + checkcert = 0 + output_file = None + verbose = 0 for opt, arg in opt_list: if opt in ("-h","--help"): @@ -430,21 +423,21 @@ if __name__ == "__main__": sys.exit() if opt in ("-c","--checkcert"): - checkcert= 1 + checkcert = 1 if opt in ("-s","--ssl"): - ssl= 1 + ssl = 1 if opt in ("-o","--output"): - output_file= arg + output_file = arg if opt == "-v": - verbose= 1 + verbose = 1 if len(arg_list) != 1: raise Exception - partialpath= arg_list[0] + partialpath = arg_list[0] if string.lower(partialpath[:4]) == "http": raise Exception @@ -453,14 +446,14 @@ if __name__ == "__main__": sys.exit(2) # got the command line args straightened out - requestor= BootServerRequest(verbose) + requestor = BootServerRequest(verbose) if output_file: - requestor.DownloadFile( partialpath, None, None, ssl, + requestor.DownloadFile(partialpath, None, None, ssl, checkcert, output_file) else: - result= requestor.MakeRequest( partialpath, None, None, ssl, checkcert) + result = requestor.MakeRequest(partialpath, None, None, ssl, checkcert) if result: - print result + print(result) else: sys.exit(1) diff --git a/source/Exceptions.py b/source/Exceptions.py index de2a670..1004d5b 100644 --- a/source/Exceptions.py +++ b/source/Exceptions.py @@ -7,15 +7,15 @@ # All rights reserved. class BootManagerException(Exception): - def __init__( self, err ): + def __init__(self, err): self.__fault= err - def __str__( self ): + def __str__(self): return self.__fault class BootManagerAuthenticationException(Exception): - def __init__( self, err ): + def __init__(self, err): self.__fault= err - def __str__( self ): + def __str__(self): return self.__fault diff --git a/source/ModelOptions.py b/source/ModelOptions.py index 3eb89ba..512348b 100644 --- a/source/ModelOptions.py +++ b/source/ModelOptions.py @@ -20,25 +20,25 @@ BADHD = 0x080 LAST = 0x100 RAWDISK = 0x200 -modeloptions = {'smp':SMP, - 'x64':X86_64, - 'i64':X86_64|INTEL, - 'a64':X86_64|AMD, - 'i32':INTEL, - 'a32':AMD, - 'numa':NUMA, - 'geode':GEODE, - 'badhd':BADHD, - 'minhw':MINHW, - 'rawdisk':RAWDISK} +modeloptions = { 'smp' : SMP, + 'x64' : X86_64, + 'i64' : X86_64|INTEL, + 'a64' : X86_64|AMD, + 'i32' : INTEL, + 'a32' : AMD, + 'numa' : NUMA, + 'geode' : GEODE, + 'badhd' : BADHD, + 'minhw' : MINHW, + 'rawdisk' : RAWDISK} def Get(model): modelinfo = string.split(model,'/') - options= 0 + options = 0 for mi in modelinfo: info = string.strip(mi) info = info.lower() - options = options | modeloptions.get(info,0) + options = options | modeloptions.get(info, 0) return options diff --git a/source/RunlevelAgent.py b/source/RunlevelAgent.py index e3047b3..012dba1 100755 --- a/source/RunlevelAgent.py +++ b/source/RunlevelAgent.py @@ -15,30 +15,30 @@ import sys import os import string -CONFIG_FILE="/tmp/source/configuration" -SESSION_FILE="/etc/planetlab/session" -RLA_PID_FILE="/var/run/rla.pid" +CONFIG_FILE = "/tmp/source/configuration" +SESSION_FILE = "/etc/planetlab/session" +RLA_PID_FILE = "/var/run/rla.pid" def read_config_file(filename): ## NOTE: text copied from BootManager.py # TODO: unify this code to make it common. i.e. use ConfigParser module vars = {} - vars_file= file(filename,'r') + vars_file = file(filename,'r') validConfFile = True for line in vars_file: # if its a comment or a whitespace line, ignore if line[:1] == "#" or string.strip(line) == "": continue - parts= string.split(line,"=") + parts = string.split(line, "=") if len(parts) != 2: - print "Invalid line in vars file: %s" % line + print "Invalid line in vars file: {}".format(line) validConfFile = False break - name= string.strip(parts[0]) - value= string.strip(parts[1]) - vars[name]= value + name = string.strip(parts[0]) + value = string.strip(parts[1]) + vars[name] = value vars_file.close() if not validConfFile: @@ -51,7 +51,7 @@ try: import plc_config api_server_url = "https://" + plc_config.PLC_API_HOST + plc_config.PLC_API_PATH except: - filename=CONFIG_FILE + filename = CONFIG_FILE vars = read_config_file(filename) api_server_url = vars['BOOT_API_SERVER'] @@ -59,15 +59,15 @@ except: class Auth: def __init__(self, username=None, password=None, **kwargs): if 'session' in kwargs: - self.auth= { 'AuthMethod' : 'session', - 'session' : kwargs['session'] } + self.auth = { 'AuthMethod' : 'session', + 'session' : kwargs['session'] } else: - if username==None and password==None: + if username is None and password is None: self.auth = {'AuthMethod': "anonymous"} else: self.auth = {'Username' : username, - 'AuthMethod' : 'password', - 'AuthString' : password} + 'AuthMethod' : 'password', + 'AuthString' : password} class PLC: def __init__(self, auth, url): self.auth = auth @@ -85,12 +85,12 @@ class PLC: return self.api.__repr__() def extract_from(filename, pattern): - f = os.popen("grep -E %s %s" % (pattern, filename)) + f = os.popen("grep -E {} {}".format(pattern, filename)) val = f.read().strip() return val def check_running(commandname): - f = os.popen("ps ax | grep -E %s | grep -v grep" % (commandname)) + f = os.popen("ps ax | grep -E {} | grep -v grep".format(commandname)) val = f.read().strip() return val @@ -100,7 +100,7 @@ def save_pid(): try: pid = os.getpid() f = open(RLA_PID_FILE, 'w') - f.write("%s\n" % pid) + f.write("{}\n".format(pid)) f.close() except: print "Uuuhhh.... this should not occur." @@ -114,8 +114,8 @@ def start_and_run(): # session file, or DNS to succeed, until AuthCheck succeeds. while True: try: - f=open(SESSION_FILE,'r') - session_str=f.read().strip() + f = open(SESSION_FILE, 'r') + session_str = f.read().strip() api = PLC(Auth(session=session_str), api_server_url) # NOTE: What should we do if this call fails? # TODO: handle dns failure here. diff --git a/source/configuration b/source/configuration index b6f0644..cbc004a 100644 --- a/source/configuration +++ b/source/configuration @@ -4,7 +4,7 @@ # the current version of the bootmanager -VERSION=5.2 +VERSION=5.3 # this is the server to contact if we don't have a bootcd DEFAULT_BOOT_SERVER=boot.planet-lab.org @@ -19,8 +19,8 @@ MONITOR_SERVER=monitor.planet-lab.org #UPLOAD_LOG_SCRIPT=/monitor/upload UPLOAD_LOG_SCRIPT=/boot/upload-bmlog.php -# bootcd variables : use %(path)s for path relative to bootcd -BOOTCD_VERSION_FILE='%(path)s/bootme/ID' +# bootcd variables : use {path} for path relative to bootcd +BOOTCD_VERSION_FILE='{path}/bootme/ID' SERVER_CERT_DIR=/tmp/source/cacert CACERT_NAME=cacert.pem diff --git a/source/notify_messages.py b/source/notify_messages.py index 682c854..61ab87b 100644 --- a/source/notify_messages.py +++ b/source/notify_messages.py @@ -11,14 +11,14 @@ this file contains the ids of messages that we can send the contacts at a site, through the BootNotifyOwners call """ -MSG_INSTALL_FINISHED= "installfinished" -MSG_INSUFFICIENT_DISK= "insufficientdisk" -MSG_INSUFFICIENT_MEMORY= "insufficientmemory" -MSG_NO_NODE_CONFIG_FILE= "noconfig" -MSG_AUTH_FAIL= "authfail" -MSG_NODE_NOT_INSTALLED= "notinstalled" -MSG_NODE_FILESYSTEM_CORRUPT= "filesystemcorrupted" -MSG_NODE_MOUNT_FAILED= "mountfailed" -MSG_NODE_MISSING_KERNEL= "missingkernel" -MSG_HOSTNAME_NOT_RESOLVE= "hostnamenotresolve" -MSG_NO_DETECTED_NETWORK= "nodetectednetwork" +MSG_INSTALL_FINISHED = "installfinished" +MSG_INSUFFICIENT_DISK = "insufficientdisk" +MSG_INSUFFICIENT_MEMORY = "insufficientmemory" +MSG_NO_NODE_CONFIG_FILE = "noconfig" +MSG_AUTH_FAIL = "authfail" +MSG_NODE_NOT_INSTALLED = "notinstalled" +MSG_NODE_FILESYSTEM_CORRUPT = "filesystemcorrupted" +MSG_NODE_MOUNT_FAILED = "mountfailed" +MSG_NODE_MISSING_KERNEL = "missingkernel" +MSG_HOSTNAME_NOT_RESOLVE = "hostnamenotresolve" +MSG_NO_DETECTED_NETWORK = "nodetectednetwork" diff --git a/source/steps/UpdateNodeConfiguration.py b/source/steps/UpdateNodeConfiguration.py index 4d16b16..26f9453 100644 --- a/source/steps/UpdateNodeConfiguration.py +++ b/source/steps/UpdateNodeConfiguration.py @@ -88,9 +88,9 @@ def Run(vars, log): except ValueError as e: pass - update_path_list = update_path_list + map(lambda x: \ - full_dir_path+"/"+x, - slices) + update_path_list = update_path_list + \ + ["{}/{}".format(full_dir_path, x) for x in slices] + except OSError as e: continue diff --git a/source/systeminfo.py b/source/systeminfo.py index 921ede6..cdbbb0d 100755 --- a/source/systeminfo.py +++ b/source/systeminfo.py @@ -34,24 +34,24 @@ a utility class for finding and returning information about block devices, memory, and other hardware on the system """ -PROC_MEMINFO_PATH= "/proc/meminfo" -PROC_PARTITIONS_PATH= "/proc/partitions" +PROC_MEMINFO_PATH = "/proc/meminfo" +PROC_PARTITIONS_PATH = "/proc/partitions" # set when the sfdisk -l trick has been done to make # all devices show up -DEVICES_SCANNED_FLAG= "/tmp/devices_scanned" +DEVICES_SCANNED_FLAG = "/tmp/devices_scanned" # a /proc/partitions block is 1024 bytes # a GB to a HDD manufacturer is 10^9 bytes BLOCKS_PER_GB = pow(10, 9) / 1024.0; -MODULE_CLASS_NETWORK= "network" -MODULE_CLASS_SCSI= "scsi" +MODULE_CLASS_NETWORK = "network" +MODULE_CLASS_SCSI = "scsi" #PCI_* is now defined in the pypci modules -#PCI_BASE_CLASS_NETWORK=0x02L -#PCI_BASE_CLASS_STORAGE=0x01L +#PCI_BASE_CLASS_NETWORK = 0x02L +#PCI_BASE_CLASS_STORAGE = 0x01L def get_total_phsyical_mem(vars = {}, log = sys.stderr): """ @@ -61,27 +61,27 @@ def get_total_phsyical_mem(vars = {}, log = sys.stderr): """ try: - meminfo_file= file(PROC_MEMINFO_PATH,"r") + meminfo_file = file(PROC_MEMINFO_PATH,"r") except IOError, e: return - total_memory= None + total_memory = None for line in meminfo_file: try: - (fieldname,value)= string.split(line,":") + (fieldname,value) = string.split(line,":") except ValueError, e: # this will happen for lines that don't have two values # (like the first line on 2.4 kernels) continue - fieldname= string.strip(fieldname) - value= string.strip(value) + fieldname = string.strip(fieldname) + value = string.strip(value) if fieldname == "MemTotal": try: - (total_memory,units)= string.split(value) + total_memory, units = string.split(value) except ValueError, e: return @@ -93,7 +93,7 @@ def get_total_phsyical_mem(vars = {}, log = sys.stderr): return try: - total_memory= int(total_memory) + total_memory = int(total_memory) except ValueError, e: return @@ -119,24 +119,23 @@ def get_block_device_list(vars = {}, log = sys.stderr): # add in valid sd and hd block device names # also check for vd (virtio devices used with kvm) for blk_prefix in ('sd','hd','vd'): - for blk_num in map ( \ - lambda x: chr(x), range(ord('a'),ord('z')+1)): - devicename="%s%c" % (blk_prefix, blk_num) - valid_blk_names[devicename]=None + for blk_num in string.ascii_lowercase: + devicename = "{}{}".format(blk_prefix, blk_num) + valid_blk_names[devicename] = None # add in valid scsi raid block device names for M in range(0,1+1): for N in range(0,7+1): devicename = "cciss/c%dd%d" % (M,N) - valid_blk_names[devicename]=None + valid_blk_names[devicename] = None for devicename in valid_blk_names.keys(): # devfs under 2.4 (old boot cds) used to list partitions # in a format such as scsi/host0/bus0/target0/lun0/disc # and /dev/sda, etc. were just symlinks try: - devfsname= os.readlink( "/dev/%s" % devicename ) - valid_blk_names[devfsname]=None + devfsname = os.readlink( "/dev/%s" % devicename ) + valid_blk_names[devfsname] = None except OSError: pass @@ -163,53 +162,53 @@ def get_block_device_list(vars = {}, log = sys.stderr): fb = open(DEVICES_SCANNED_FLAG,"w") fb.close() - devicelist= {} + devicelist = {} - partitions_file= file(PROC_PARTITIONS_PATH,"r") - line_count= 0 + partitions_file = file(PROC_PARTITIONS_PATH,"r") + line_count = 0 for line in partitions_file: - line_count= line_count + 1 + line_count = line_count + 1 # skip the first two lines always if line_count < 2: continue - parts= string.split(line) + parts = string.split(line) if len(parts) < 4: continue - device= parts[3] + device = parts[3] # skip and ignore any partitions if not valid_blk_names.has_key(device): continue try: - major= int(parts[0]) - minor= int(parts[1]) - blocks= int(parts[2]) + major = int(parts[0]) + minor = int(parts[1]) + blocks = int(parts[2]) except ValueError, err: continue - gb_size= blocks/BLOCKS_PER_GB + gb_size = blocks/BLOCKS_PER_GB # check to see if the blk device is readonly try: # can we write to it? - dev_name= "/dev/%s" % device + dev_name = "/dev/%s" % device fb = open(dev_name,"w") fb.close() - readonly=False + readonly = False except IOError, e: # check if EROFS errno if errno.errorcode.get(e.errno,None) == 'EROFS': - readonly=True + readonly = True else: # got some other errno, pretend device is readonly - readonly=True + readonly = True - devicelist[dev_name]= (major,minor,blocks,gb_size,readonly) + devicelist[dev_name] = (major,minor,blocks,gb_size,readonly) return devicelist @@ -238,8 +237,8 @@ def get_system_modules( vars = {}, log = sys.stderr): """ if not vars.has_key("SYSIMG_PATH"): - vars["SYSIMG_PATH"]="/" - SYSIMG_PATH=vars["SYSIMG_PATH"] + vars["SYSIMG_PATH"] = "/" + SYSIMG_PATH = vars["SYSIMG_PATH"] if not vars.has_key("NODE_MODEL_OPTIONS"): vars["NODE_MODEL_OPTIONS"] = 0; @@ -249,7 +248,7 @@ def get_system_modules( vars = {}, log = sys.stderr): # get the kernel version we are assuming if kernel_version is None: try: - kernel_version= os.listdir( "%s/lib/modules/" % SYSIMG_PATH ) + kernel_version = os.listdir( "%s/lib/modules/" % SYSIMG_PATH ) except OSError, e: return @@ -259,7 +258,7 @@ def get_system_modules( vars = {}, log = sys.stderr): if len(kernel_version) > 1: print( "WARNING: We may be returning modules for the wrong kernel." ) - kernel_version= kernel_version[0] + kernel_version = kernel_version[0] print( "Using kernel version %s" % kernel_version ) @@ -273,16 +272,16 @@ def get_system_modules( vars = {}, log = sys.stderr): pcimap = pypcimap.PCIMap(modules_pcimap_path) # this is the actual data structure we return - system_mods= {} + system_mods = {} # these are the lists that will be in system_mods - network_mods= [] - scsi_mods= [] + network_mods = [] + scsi_mods = [] # XXX: this is really similar to what BootCD/conf_files/pl_hwinit does. merge? pcidevs = get_devices() - devlist=pcidevs.keys() + devlist =pcidevs.keys() devlist.sort() for slot in devlist: dev = pcidevs[slot] @@ -294,7 +293,7 @@ def get_system_modules( vars = {}, log = sys.stderr): # claims to be a Bridge, even though it is clearly a # network device if "forcedeth" in modules: - base=PCI_BASE_CLASS_NETWORK + base = PCI_BASE_CLASS_NETWORK else: continue @@ -304,8 +303,8 @@ def get_system_modules( vars = {}, log = sys.stderr): elif base == PCI_BASE_CLASS_STORAGE: scsi_mods += modules - system_mods[MODULE_CLASS_SCSI]= scsi_mods - system_mods[MODULE_CLASS_NETWORK]= network_mods + system_mods[MODULE_CLASS_SCSI] = scsi_mods + system_mods[MODULE_CLASS_NETWORK] = network_mods return system_mods @@ -313,11 +312,11 @@ def get_system_modules( vars = {}, log = sys.stderr): def getKernelVersion( vars = {} , log = sys.stderr): # make sure we have the variables we need try: - SYSIMG_PATH= vars["SYSIMG_PATH"] + SYSIMG_PATH = vars["SYSIMG_PATH"] if SYSIMG_PATH == "": raise ValueError, "SYSIMG_PATH" - NODE_MODEL_OPTIONS=vars["NODE_MODEL_OPTIONS"] + NODE_MODEL_OPTIONS = vars["NODE_MODEL_OPTIONS"] except KeyError, var: raise BootManagerException, "Missing variable in vars: %s\n" % var except ValueError, var: @@ -338,8 +337,8 @@ def getKernelVersion( vars = {} , log = sys.stderr): log.write( "WARNING: Couldn't locate smp kernel.\n") option = '' try: - initrd= os.readlink( "%s/boot/initrd-boot%s" % (SYSIMG_PATH,option) ) - kernel_version= initrd.replace("initrd-", "").replace(".img", "") + initrd = os.readlink( "%s/boot/initrd-boot%s" % (SYSIMG_PATH,option) ) + kernel_version = initrd.replace("initrd-", "").replace(".img", "") except OSError, e: initrd = None kernel_version = None @@ -348,7 +347,7 @@ def getKernelVersion( vars = {} , log = sys.stderr): if __name__ == "__main__": - devices= get_block_device_list() + devices = get_block_device_list() print "block devices detected:" if not devices: print "no devices found!" @@ -358,7 +357,7 @@ if __name__ == "__main__": print "" - memory= get_total_phsyical_mem() + memory = get_total_phsyical_mem() if not memory: print "unable to read /proc/meminfo for memory" else: @@ -371,7 +370,7 @@ if __name__ == "__main__": if len(sys.argv) > 2: kernel_version = sys.argv[1] - modules= get_system_modules() + modules = get_system_modules() if not modules: print "unable to list system modules" else: diff --git a/source/utils.py b/source/utils.py index 3c6c225..5ad3ec7 100644 --- a/source/utils.py +++ b/source/utils.py @@ -32,55 +32,55 @@ import select, sys, string # enabling this will cause the node to ask for breakpoint-mode at startup # production code should read False/False -PROMPT_MODE=False +PROMPT_MODE = False # default for when prompt is turned off, or it's on but the timeout triggers -BREAKPOINT_MODE=False +BREAKPOINT_MODE = False # verbose mode is just fine -VERBOSE_MODE=True +VERBOSE_MODE = True # in seconds : if no input, proceed -PROMPT_TIMEOUT=5 +PROMPT_TIMEOUT = 5 def prompt_for_breakpoint_mode (): global BREAKPOINT_MODE if PROMPT_MODE: - default_answer=BREAKPOINT_MODE - answer='' + default_answer = BREAKPOINT_MODE + answer = '' if BREAKPOINT_MODE: - display="[y]/n" + display = "[y]/n" else: - display="y/[n]" - sys.stdout.write ("Want to run in breakpoint mode ? %s "%display) + display = "y/[n]" + sys.stdout.write ("Want to run in breakpoint mode ? {} ".format(display)) sys.stdout.flush() - r,w,e = select.select ([sys.stdin],[],[],PROMPT_TIMEOUT) + r, w, e = select.select ([sys.stdin], [], [], PROMPT_TIMEOUT) if r: answer = string.strip(sys.stdin.readline()) else: - sys.stdout.write("\nTimed-out (%d s)"%PROMPT_TIMEOUT) + sys.stdout.write("\nTimed-out ({}s)".format(PROMPT_TIMEOUT)) if answer: - BREAKPOINT_MODE = ( answer == "y" or answer == "Y") + BREAKPOINT_MODE = (answer == "y" or answer == "Y") else: BREAKPOINT_MODE = default_answer - label="Off" + label = "Off" if BREAKPOINT_MODE: - label="On" - sys.stdout.write("\nCurrent BREAKPOINT_MODE is %s\n"%label) + label = "On" + sys.stdout.write("\nCurrent BREAKPOINT_MODE is {}\n".format(label)) def breakpoint (message, cmd = None): if BREAKPOINT_MODE: if cmd is None: - cmd="/bin/sh" - message=message+" -- Entering bash - type ^D to proceed" + cmd = "/bin/sh" + message = message + " -- Entering bash - type ^D to proceed" print message os.system(cmd) ######################################## -def makedirs( path ): +def makedirs(path): """ from python docs for os.makedirs: Throws an error exception if the leaf directory @@ -93,37 +93,37 @@ def makedirs( path ): otherwise. Does not test the writability of said directory. """ try: - os.makedirs( path ) + os.makedirs(path) except OSError: pass try: - os.listdir( path ) + os.listdir(path) except OSError: - raise BootManagerException, "Unable to create directory tree: %s" % path + raise BootManagerException("Unable to create directory tree: {}".format(path)) return 1 -def removedir( path ): +def removedir(path): """ remove a directory tree, return 1 if successful, a BootManagerException if failure. """ try: - os.listdir( path ) + os.listdir(path) except OSError: return 1 try: - shutil.rmtree( path ) - except OSError, desc: - raise BootManagerException, "Unable to remove directory tree: %s" % path + shutil.rmtree(path) + except OSError as desc: + raise BootManagerException("Unable to remove directory tree: {}".format(path)) return 1 -def sysexec( cmd, log=None, fsck=False, shell=False ): +def sysexec(cmd, log=None, fsck=False, shell=False): """ execute a system command, output the results to the logger if log <> None @@ -140,30 +140,30 @@ def sysexec( cmd, log=None, fsck=False, shell=False ): if shell or cmd.__contains__(">"): prog = subprocess.Popen(cmd, shell=True) if log is not None: - log.write("sysexec (shell mode) >>> %s" % cmd) + log.write("sysexec (shell mode) >>> {}".format(cmd)) if VERBOSE_MODE: - print "sysexec (shell mode) >>> %s" % cmd + print "sysexec (shell mode) >>> {}".format(cmd) else: prog = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE) if log is not None: - log.write("sysexec >>> %s\n" % cmd) + log.write("sysexec >>> {}\n".format(cmd)) if VERBOSE_MODE: - print "sysexec >>> %s" % cmd + print "sysexec >>> {}".format(cmd) except OSError: - raise BootManagerException, \ - "Unable to create instance of subprocess.Popen " \ - "for command: %s" % cmd + raise BootManagerException( + "Unable to create instance of subprocess.Popen " + "for command: {}".format(cmd)) try: (stdoutdata, stderrdata) = prog.communicate() except KeyboardInterrupt: - raise BootManagerException, "Interrupted by user" + raise BootManagerException("Interrupted by user") # log stdout & stderr if log is not None: if stdoutdata: - log.write("==========stdout\n"+stdoutdata) + log.write("==========stdout\n" + stdoutdata) if stderrdata: - log.write("==========stderr\n"+stderrdata) + log.write("==========stderr\n" + stderrdata) returncode = prog.wait() @@ -178,16 +178,16 @@ def sysexec( cmd, log=None, fsck=False, shell=False ): # 32 - Fsck canceled by user request # 128 - Shared library error if returncode != 0 and returncode != 1: - raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode) + raise BootManagerException("Running {} failed (rc={})".format(cmd, returncode)) else: if returncode != 0: - raise BootManagerException, "Running %s failed (rc=%d)" % (cmd,returncode) + raise BootManagerException("Running {} failed (rc={})".format(cmd, returncode)) prog = None return 1 -def sysexec_chroot( path, cmd, log=None, shell=False): +def sysexec_chroot(path, cmd, log=None, shell=False): """ same as sysexec, but inside a chroot """ @@ -195,61 +195,61 @@ def sysexec_chroot( path, cmd, log=None, shell=False): release = os.uname()[2] # 2.6.12 kernels need this if release[:5] == "2.6.1": - library = "%s/lib/libc-opendir-hack.so" % path + library = "{}/lib/libc-opendir-hack.so".format(path) if not os.path.exists(library): shutil.copy("./libc-opendir-hack.so", library) preload = "/bin/env LD_PRELOAD=/lib/libc-opendir-hack.so" - sysexec("chroot %s %s %s" % (path, preload, cmd), log, shell=shell) + sysexec("chroot {} {} {}".format(path, preload, cmd), log, shell=shell) -def sysexec_chroot_noerr( path, cmd, log=None, shell=False ): +def sysexec_chroot_noerr(path, cmd, log=None, shell=False): """ same as sysexec_chroot, but capture boot manager exceptions """ try: - rc= 0 - rc= sysexec_chroot( cmd, log, shell=shell ) - except BootManagerException, e: + rc = 0 + rc = sysexec_chroot(cmd, log, shell=shell) + except BootManagerException as e: pass return rc -def sysexec_noerr( cmd, log=None, shell=False ): +def sysexec_noerr(cmd, log=None, shell=False): """ same as sysexec, but capture boot manager exceptions """ try: rc= 0 - rc= sysexec( cmd, log, shell=shell ) - except BootManagerException, e: + rc= sysexec(cmd, log, shell=shell) + except BootManagerException as e: pass return rc -def chdir( dir ): +def chdir(dir): """ change to a directory, return 1 if successful, a BootManagerException if failure """ try: - os.chdir( dir ) + os.chdir(dir) except OSError: - raise BootManagerException, "Unable to change to directory: %s" % dir + raise BootManagerException("Unable to change to directory: {}".format(dir)) return 1 -def removefile( filepath ): +def removefile(filepath): """ removes a file, return 1 if successful, 0 if failure """ try: - os.remove( filepath ) + os.remove(filepath) except OSError: - raise BootManagerException, "Unable to remove file: %s" % filepath + raise BootManagerException("Unable to remove file: {}".format(filepath)) return 1 @@ -258,9 +258,6 @@ def removefile( filepath ): # from: http://forums.devshed.com/archive/t-51149/ # Ethernet-card-address-Through-Python-or-C -def hexy(n): - return "%02x" % (ord(n)) - def get_mac_from_interface(ifname): """ given a device name, like eth0, return its mac_address. @@ -269,15 +266,14 @@ def get_mac_from_interface(ifname): SIOCGIFHWADDR = 0x8927 # magic number - s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) + s = socket.socket(socket.AF_INET,socket.SOCK_STREAM) ifname = string.strip(ifname) ifr = ifname + '\0'*(32-len(ifname)) try: - r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr) - addr = map(hexy,r[18:24]) - ret = (':'.join(map(str, addr))) - except IOError, e: + r = fcntl.ioctl(s.fileno(), SIOCGIFHWADDR,ifr) + ret = ':'.join(["{:02x}".format(ord(n)) for n in r[18:24]]) + except IOError as e: ret = None return ret @@ -294,7 +290,7 @@ def sha1_file(filename): m = hashlib.sha1() except: import sha - m=sha.new() + m = sha.new() f = file(filename, 'rb') while True: # 256 KB seems ideal for speed/memory tradeoff @@ -311,4 +307,4 @@ def sha1_file(filename): del block return m.hexdigest() except IOError: - raise BootManagerException, "Cannot calculate SHA1 hash of %s" % filename + raise BootManagerException("Cannot calculate SHA1 hash of {}".format(filename)) -- 2.43.0