diff --git a/XSConsole.py b/XSConsole.py index 234886b..b783084 100755 --- a/XSConsole.py +++ b/XSConsole.py @@ -27,15 +27,15 @@ def main(): if '--shelltimeout' in sys.argv: # Print a shell timeout value, suitable for TMOUT=`xsconsole --shelltimeout` if Config.Inst().AllShellsTimeout(): - print State.Inst().AuthTimeoutSeconds() + print(State.Inst().AuthTimeoutSeconds()) else: - print + print() else: app = App.Inst() app.Build( ['plugins-base', 'plugins-oem', 'plugins-extras'] ) try: app.Enter() - except Exception, e: + except Exception as e: # it may be that the screen size has changed app.AssertScreenSize() # if we get here then it was some other problem @@ -44,7 +44,7 @@ def main(): if __name__ == "__main__": try: main() - except Exception, e: + except Exception as e: # Add backtrace to log try: trace = traceback.format_tb(sys.exc_info()[2]) diff --git a/XSConsoleAuth.py b/XSConsoleAuth.py index 2a6f06d..a1cd49b 100644 --- a/XSConsoleAuth.py +++ b/XSConsoleAuth.py @@ -15,10 +15,7 @@ import os, spwd, re, sys, time, socket -try: - import PAM # From PyPAM RPM -except ImportError: - import pam as PAM # From pip install python-pam +import pam from XSConsoleBases import * from XSConsoleLang import * @@ -109,26 +106,7 @@ def TCPAuthenticate(self, inUsername, inPassword): session.close() def PAMAuthenticate(self, inUsername, inPassword): - - def PAMConv(inAuth, inQueryList, *theRest): - # *theRest consumes the userData argument from later versions of PyPAM - retVal = [] - for query in inQueryList: - if query[1] == PAM.PAM_PROMPT_ECHO_ON or query[1] == PAM.PAM_PROMPT_ECHO_OFF: - # Return inPassword from the scope that encloses this function - retVal.append((inPassword, 0)) # Append a tuple with two values (so double brackets) - return retVal - - auth = PAM.pam() - auth.start('passwd') - auth.set_item(PAM.PAM_USER, inUsername) - auth.set_item(PAM.PAM_CONV, PAMConv) - - try: - auth.authenticate() - auth.acct_mgmt() - # No exception implies a successful login - except Exception, e: + if not pam.authenticate(inUsername, inPassword): # Display a generic message for all failures raise Exception(Lang("The system could not log you in. Please check your access credentials and try again.")) @@ -188,7 +166,7 @@ def OpenSession(self): session = None self.masterConnectionBroken = True self.error = 'The master connection has timed out.' - except Exception, e: + except Exception as e: session = None self.error = e @@ -198,7 +176,7 @@ def OpenSession(self): try: session.login_with_password('root', self.defaultPassword,'','XSConsole') - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'HOST_IS_SLAVE': # Ignore slave errors when testing session = None self.error = e @@ -206,7 +184,7 @@ def OpenSession(self): session = None self.masterConnectionBroken = True self.error = 'The master connection has timed out.' - except Exception, e: + except Exception as e: session = None self.error = e return session @@ -218,7 +196,7 @@ def CloseSession(self, inSession): if inSession._session is not None: try: inSession.logout() - except XenAPI.Failure, e: + except XenAPI.Failure as e: XSLog('XAPI Failed to logout exception was ', e) return None @@ -241,7 +219,7 @@ def ChangePassword(self, inOldPassword, inNewPassword): if self.IsPasswordSet(): try: self.PAMAuthenticate('root', inOldPassword) - except Exception, e: + except Exception as e: raise Exception(Lang('Old password not accepted. Please check your access credentials and try again.')) self.AssertAuthenticated() @@ -252,7 +230,7 @@ def ChangePassword(self, inOldPassword, inNewPassword): session.xenapi.session.change_password(inOldPassword, inNewPassword) finally: self.CloseSession(session) - except Exception, e: + except Exception as e: ShellPipe("/usr/bin/passwd", "--stdin", "root").Call(inNewPassword) raise Exception(Lang("The underlying Xen API xapi could not be used. Password changed successfully on this host only.")) diff --git a/XSConsoleBases.py b/XSConsoleBases.py index 5de2ef6..3a6b8a4 100644 --- a/XSConsoleBases.py +++ b/XSConsoleBases.py @@ -22,7 +22,7 @@ def ParamsToAttr(): d = inspect.currentframe().f_back.f_locals obj = d.pop("self") - for name, value in d.iteritems(): + for name, value in d.items(): setattr(obj, name,value) def FirstValue(*inArgs): @@ -33,7 +33,7 @@ def FirstValue(*inArgs): class Struct: def __init__(self, *inArgs, **inKeywords): - for k, v in inKeywords.items(): + for k, v in list(inKeywords.items()): setattr(self, k, v) def __repr__(self): diff --git a/XSConsoleCurses.py b/XSConsoleCurses.py index 7881cd6..f97da43 100644 --- a/XSConsoleCurses.py +++ b/XSConsoleCurses.py @@ -13,13 +13,14 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -import curses, sys, commands +import curses, sys, subprocess from XSConsoleBases import * from XSConsoleConfig import * from XSConsoleLang import * from XSConsoleState import * + class CursesPalette: pairIndex = 1 colours = {} @@ -93,7 +94,7 @@ def DefineColours(cls): 'MODAL_SELECTED', 'MODAL_FLASH', 'HELP_BASE', 'HELP_BRIGHT', 'HELP_FLASH', 'TOPLINE_BASE']: cls.colours[name] = curses.color_pair(0) - for key, value in cls.colours.items(): + for key, value in list(cls.colours.items()): if key.endswith('_SELECTED'): cls.colours[key] |= curses.A_REVERSE elif key.endswith('_FLASH'): @@ -174,13 +175,13 @@ def ClippedAddStr(self, inString, inX, inY, inColour): # Internal use if len(clippedStr) > 0: try: encodedStr = clippedStr - if isinstance(clippedStr, unicode): - encodedStr = clippedStr.encode('utf-8') + if isinstance(clippedStr, bytes): + encodedStr = clippedStr.decode('utf-8') # Clear field here since addstr will clear len(encodedStr)-len(clippedStr) too few spaces self.win.addstr(inY, xPos, len(clippedStr)*' ', CursesPalette.ColourAttr(FirstValue(inColour, self.defaultColour))) self.win.refresh() self.win.addstr(inY, xPos, encodedStr, CursesPalette.ColourAttr(FirstValue(inColour, self.defaultColour))) - except Exception, e: + except Exception as e: if xPos + len(inString) == self.xSize and inY + 1 == self.ySize: # Curses incorrectly raises an exception when writing the bottom right # character in a window, but still completes the write, so ignore it @@ -212,7 +213,7 @@ def AddWrappedText(self, inString, inX, inY, inColour = None): yPos += 1 def AddHCentredText(self, inString, inY, inColour = None): - xStart = self.xSize / 2 - len(inString) / 2 + xStart = self.xSize // 2 - len(inString) // 2 self.ClippedAddStr(inString, xStart, inY, inColour) def Decorate(self): diff --git a/XSConsoleData.py b/XSConsoleData.py index dde81a9..38675e5 100644 --- a/XSConsoleData.py +++ b/XSConsoleData.py @@ -15,7 +15,7 @@ import XenAPI import datetime -import commands, re, shutil, sys, tempfile, socket, os +import subprocess, re, shutil, sys, tempfile, socket, os from pprint import pprint from simpleconfig import SimpleConfigFile @@ -65,7 +65,7 @@ def DataCache(self): def GetData(self, inNames, inDefault = None): data = self.data for name in inNames: - if name is '__repr__': + if name == '__repr__': # Error - missing () raise Exception('Data call Data.' + '.'.join(inNames[:-1]) + ' must end with ()') elif name in data: @@ -98,31 +98,31 @@ def Create(self): self.ReadTimezones() self.ReadKeymaps() - (status, output) = commands.getstatusoutput("dmidecode") + (status, output) = subprocess.getstatusoutput("dmidecode") if status != 0: # Use test dmidecode file if there's no real output - (status, output) = commands.getstatusoutput("/bin/cat ./dmidecode.txt") + (status, output) = subprocess.getstatusoutput("/bin/cat ./dmidecode.txt") if status == 0: self.ScanDmiDecode(output.split("\n")) - (status, output) = commands.getstatusoutput("/sbin/lspci -m") + (status, output) = subprocess.getstatusoutput("/sbin/lspci -m") if status != 0: - (status, output) = commands.getstatusoutput("/usr/bin/lspci -m") + (status, output) = subprocess.getstatusoutput("/usr/bin/lspci -m") if status == 0: self.ScanLspci(output.split("\n")) if os.path.isfile("/usr/bin/ipmitool"): - (status, output) = commands.getstatusoutput("/usr/bin/ipmitool mc info") + (status, output) = subprocess.getstatusoutput("/usr/bin/ipmitool mc info") if status == 0: self.ScanIpmiMcInfo(output.split("\n")) - (status, output) = commands.getstatusoutput("/bin/cat /etc/xensource-inventory") + (status, output) = subprocess.getstatusoutput("/bin/cat /etc/xensource-inventory") if status == 0: self.ScanInventory(output.split("\n")) - (status, output) = commands.getstatusoutput("/usr/bin/openssl x509 -in %s/xapi-ssl.pem -fingerprint -noout" % (Config.Inst().XCPConfigDir())) + (status, output) = subprocess.getstatusoutput("/usr/bin/openssl x509 -in %s/xapi-ssl.pem -fingerprint -noout" % (Config.Inst().XCPConfigDir())) if status == 0: fp = output.split("=") if len(fp) >= 2: @@ -164,7 +164,7 @@ def Update(self): try: try: thisHost = self.session.xenapi.session.get_this_host(self.session._session) - except XenAPI.Failure, e: + except XenAPI.Failure as e: XSLog('Data update connection failed - retrying. Exception was:', e) self.session = Auth.Inst().CloseSession(self.session) self.RequireSession() @@ -192,7 +192,7 @@ def Update(self): self.data['host']['crash_dump_sr'] = None convertCPU = lambda cpu: self.session.xenapi.host_cpu.get_record(cpu) - self.data['host']['host_CPUs'] = map(convertCPU, self.data['host']['host_CPUs']) + self.data['host']['host_CPUs'] = list(map(convertCPU, self.data['host']['host_CPUs'])) def convertPIF(inPIF): retVal = self.session.xenapi.PIF.get_record(inPIF) @@ -203,13 +203,13 @@ def convertPIF(inPIF): try: retVal['network'] = self.session.xenapi.network.get_record(retVal['network']) - except XenAPI.Failure, e: + except XenAPI.Failure as e: XSLogError('Missing network record: ', e) retVal['opaqueref'] = inPIF return retVal - self.data['host']['PIFs'] = map(convertPIF, self.data['host']['PIFs']) + self.data['host']['PIFs'] = list(map(convertPIF, self.data['host']['PIFs'])) # Create missing PIF names for pif in self.data['host']['PIFs']: @@ -221,7 +221,7 @@ def convertPIF(inPIF): pif['metrics']['device_name'] = Lang('') # Sort PIFs by device name for consistent order - self.data['host']['PIFs'].sort(lambda x, y : cmp(x['device'], y['device'])) + self.data['host']['PIFs'].sort(key=lambda pif: pif['device']) def convertVBD(inVBD): retVBD = self.session.xenapi.VBD.get_record(inVBD) @@ -230,7 +230,7 @@ def convertVBD(inVBD): def convertVDI(inVDI): retVDI = self.session.xenapi.VDI.get_record(inVDI) - retVDI['VBDs'] = map(convertVBD, retVDI['VBDs']) + retVDI['VBDs'] = list(map(convertVBD, retVDI['VBDs'])) retVDI['opaqueref'] = inVDI return retVDI @@ -246,14 +246,14 @@ def convertPBD(inPBD): if retPBD['SR'] is not None: retPBD['SR']['opaqueref'] = srRef if retPBD['SR'].get('type', '') == 'udev': - retPBD['SR']['VDIs'] = map(convertVDI, retPBD['SR']['VDIs']) + retPBD['SR']['VDIs'] = list(map(convertVDI, retPBD['SR']['VDIs'])) for vdi in retPBD['SR']['VDIs']: vdi['SR'] = retPBD['SR'] retPBD['opaqueref'] = inPBD return retPBD - self.data['host']['PBDs'] = map(convertPBD, self.data['host']['PBDs']) + self.data['host']['PBDs'] = list(map(convertPBD, self.data['host']['PBDs'])) # Only load the to DOM-0 VM to save time vmList = self.data['host']['resident_VMs'] @@ -301,12 +301,12 @@ def update_SR_reference(inPool, retPool, key): return retPool self.data['pools'] = {} - for id, pool in pools.iteritems(): + for id, pool in pools.items(): self.data['pools'][id] = convertPool(id, pool) except socket.timeout: self.session = None - except Exception, e: + except Exception as e: XSLogError('Data update failed: ', e) try: @@ -317,7 +317,7 @@ def update_SR_reference(inPool, retPool, key): pbdRefs.append(pbd['opaqueref']) srMap= self.session.xenapi.SR.get_all_records() - for opaqueRef, values in srMap.iteritems(): + for opaqueRef, values in srMap.items(): values['opaqueref'] = opaqueRef values['islocal'] = False for pbdRef in values.get('PBDs', []): @@ -326,7 +326,7 @@ def update_SR_reference(inPool, retPool, key): self.data['sr'].append(values) - except Exception, e: + except Exception as e: XSLogError('SR data update failed: ', e) self.UpdateFromResolveConf() @@ -454,22 +454,22 @@ def LoggingDestinationSet(self, inDestination): self.session.xenapi.host.syslog_reconfigure(self.host.opaqueref()) def UpdateFromResolveConf(self): - (status, output) = commands.getstatusoutput("/usr/bin/grep -v \"^;\" /etc/resolv.conf") + (status, output) = subprocess.getstatusoutput("/usr/bin/grep -v \"^;\" /etc/resolv.conf") if status == 0: self.ScanResolvConf(output.split("\n")) def UpdateFromSysconfig(self): - (status, output) = commands.getstatusoutput("/bin/cat /etc/sysconfig/network") + (status, output) = subprocess.getstatusoutput("/bin/cat /etc/sysconfig/network") if status == 0: self.ScanSysconfigNetwork(output.split("\n")) def UpdateFromHostname(self): - (status, output) = commands.getstatusoutput("/bin/cat /etc/hostname") + (status, output) = subprocess.getstatusoutput("/bin/cat /etc/hostname") if status == 0: self.ScanHostname(output.split("\n")) def UpdateFromNTPConf(self): - (status, output) = commands.getstatusoutput("/bin/cat /etc/chrony.conf") + (status, output) = subprocess.getstatusoutput("/bin/cat /etc/chrony.conf") if status == 0: self.ScanNTPConf(output.split("\n")) @@ -477,7 +477,7 @@ def StringToBool(self, inString): return inString.lower().startswith('true') def RootLabel(self): - output = commands.getoutput('/bin/cat /proc/cmdline') + output = subprocess.getoutput('/bin/cat /proc/cmdline') match = re.search(r'root=\s*LABEL\s*=\s*(\S+)', output) if match: retVal = match.group(1) @@ -623,7 +623,7 @@ def Match(self, inLine, inRegExp, inKey): def MultipleMatch(self, inLine, inRegExp, inKey): match = re.match(inRegExp, inLine) if match: - if not self.data['dmi'].has_key(inKey): + if inKey not in self.data['dmi']: self.data['dmi'][inKey] = [] self.data['dmi'][inKey].append(match.group(1)) @@ -675,7 +675,7 @@ def ScanIpmiMcInfo(self, inLines): self.data['bmc']['version'] = match.group(1) def ScanService(self, service): - (status, output) = commands.getstatusoutput("systemctl is-enabled %s" % (service,)) + (status, output) = subprocess.getstatusoutput("systemctl is-enabled %s" % (service,)) self.data['chkconfig'][service] = status == 0 def ScanResolvConf(self, inLines): @@ -745,7 +745,7 @@ def ReadTimezones(self): 'cities' : {} } - filterExp = re.compile('('+'|'.join(self.data['timezones']['continents'].values())+')') + filterExp = re.compile('('+'|'.join(list(self.data['timezones']['continents'].values()))+')') zonePath = '/usr/share/zoneinfo' for root, dirs, files in os.walk(zonePath): @@ -779,7 +779,7 @@ def TimezoneSet(self, inTimezone): cfg.write('/etc/sysconfig/clock') def CurrentTimeString(self): - return commands.getoutput('/bin/date -R') + return subprocess.getoutput('/bin/date -R') def ReadKeymaps(self): self.data['keyboard'] = { @@ -800,7 +800,7 @@ def ReadKeymaps(self): self.data['keyboard']['keymaps'][match.group(1)] = filePath self.data['keyboard']['namestomaps'] = Keymaps.NamesToMaps() - for value in self.data['keyboard']['namestomaps'].values(): + for value in list(self.data['keyboard']['namestomaps'].values()): if not value in self.data['keyboard']['keymaps']: XSLogError("Warning: Missing keymap " + value) @@ -811,7 +811,7 @@ def KeymapSet(self, inKeymap): keymapParam = ShellUtils.MakeSafeParam(inKeymap) # Load the keymap now - status, output = commands.getstatusoutput('/bin/loadkeys "'+keymapParam+'"') + status, output = subprocess.getstatusoutput('/bin/loadkeys "'+keymapParam+'"') if status != 0: raise Exception(output) @@ -827,7 +827,7 @@ def KeymapSet(self, inKeymap): def KeymapToName(self, inKeymap): # Derive a name to present to the user mapName = FirstValue(inKeymap, Lang('')) - for key, value in self.keyboard.namestomaps({}).iteritems(): + for key, value in self.keyboard.namestomaps({}).items(): if value == inKeymap: mapName = key @@ -900,7 +900,7 @@ def SetPoolSRsFromDeviceIfNotSet(self, inDevice): def GetPoolForThisHost(self): self.RequireSession() retVal = None - for pool in self.pools({}).values(): + for pool in list(self.pools({}).values()): # Currently there is only one pool retVal = pool break @@ -914,7 +914,7 @@ def ReconfigureManagement(self, inPIF, inMode, inIP, inNetmask, inGateway, in self.RequireSession() self.session.xenapi.PIF.reconfigure_ip(inPIF['opaqueref'], inMode, inIP, inNetmask, inGateway, FirstValue(inDNS, '')) self.session.xenapi.host.management_reconfigure(inPIF['opaqueref']) - status, output = commands.getstatusoutput('%s host-signal-networking-change' % (Config.Inst().XECLIPath())) + status, output = subprocess.getstatusoutput('%s host-signal-networking-change' % (Config.Inst().XECLIPath())) if status != 0: raise Exception(output) finally: @@ -1040,13 +1040,13 @@ def PurgeVBDs(self): if 'xsconsole_tmp' in vbd.get('other_config', {}): vbdRefs[ vbd['opaqueref'] ] = vbd - for vbd in vbdRefs.values(): + for vbd in list(vbdRefs.values()): try: # Currently this won't destroy mounted VBDs if vbd['currently_attached']: self.UnplugVBD(vbd) self.DestroyVBD(vbd) - except Exception, e: + except Exception as e: XSLogError('VBD purge failed', e) def IsXAPIRunning(self): @@ -1058,7 +1058,7 @@ def IsXAPIRunning(self): pidfile = "/var/run/xapi.pid" if pidfile: # Look for any "xapi" running - pid = file(pidfile).read().strip() + pid = open(pidfile, "r").read().strip() exelink = "/proc/%s/exe" % (pid) if os.path.exists(exelink): if os.path.basename(os.readlink(exelink)) == "xapi": @@ -1090,32 +1090,32 @@ def StartXAPI(self): State.Inst().SaveIfRequired() def EnableService(self, service): - status, output = commands.getstatusoutput("systemctl enable %s" % (service,)) + status, output = subprocess.getstatusoutput("systemctl enable %s" % (service,)) if status != 0: raise Exception(output) def DisableService(self, service): - status, output = commands.getstatusoutput("systemctl disable %s" % (service,)) + status, output = subprocess.getstatusoutput("systemctl disable %s" % (service,)) if status != 0: raise Exception(output) def RestartService(self, service): - status, output = commands.getstatusoutput("systemctl restart %s" % (service,)) + status, output = subprocess.getstatusoutput("systemctl restart %s" % (service,)) if status != 0: raise Exception(output) def StartService(self, service): - status, output = commands.getstatusoutput("systemctl start %s" % (service,)) + status, output = subprocess.getstatusoutput("systemctl start %s" % (service,)) if status != 0: raise Exception(output) def StopService(self, service): - status, output = commands.getstatusoutput("systemctl stop %s" % (service,)) + status, output = subprocess.getstatusoutput("systemctl stop %s" % (service,)) if status != 0: raise Exception(output) def NTPStatus(self): - status, output = commands.getstatusoutput("/usr/bin/ntpstat") + status, output = subprocess.getstatusoutput("/usr/bin/ntpstat") return output def SetVerboseBoot(self, inVerbose): @@ -1124,7 +1124,7 @@ def SetVerboseBoot(self, inVerbose): else: name = 'quiet' - status, output = commands.getstatusoutput( + status, output = subprocess.getstatusoutput( "(export TERM=xterm && /opt/xensource/libexec/set-boot " + name + ")") if status != 0: raise Exception(output) diff --git a/XSConsoleDataUtils.py b/XSConsoleDataUtils.py index d39d5d0..587a68f 100644 --- a/XSConsoleDataUtils.py +++ b/XSConsoleDataUtils.py @@ -73,7 +73,7 @@ def DeviceList(cls, inWritableOnly): name = "%-50s%10.10s%10.10s" % (nameDesc[:50], nameLabel[:10], nameSize[:10]) retVal.append(Struct(name = name, vdi = vdi)) - retVal.sort(lambda x, y : cmp(x.vdi['name_label'], y.vdi['name_label'])) + retVal.sort(key=lambda data: data.vdi['name_label']) return retVal @@ -130,7 +130,7 @@ def SizeString(cls, inSizeOrFilename, inDefault = None): else: retVal = str(int(fileSize)) - except Exception, e: + except Exception as e: retVal = FirstValue(inDefault, '') return retVal @@ -164,7 +164,7 @@ def USBFormat(self, inVDI): try: popenObj.wait() # Must wait for completion before mkfs break - except IOError, e: + except IOError as e: if e.errno != errno.EINTR: # Loop if EINTR raise @@ -241,17 +241,17 @@ def __init__(self, inVDI, inMode = None): if status != 0: try: self.Unmount() - except Exception, e: + except Exception as e: XSLogFailure('Device failed to unmount', e) output += '\n'+self.mountDev self.HandleMountFailure(output.split("\n")) self.mountedVBD = True - except Exception, e: + except Exception as e: try: self.Unmount() - except Exception, e: + except Exception as e: # Report the original exception, not this one XSLogFailure('Device failed to unmount', e) raise e @@ -324,7 +324,7 @@ def Unmount(self): time.sleep(5) try: self.vbd = Data.Inst().UnplugVBD(self.vbd) - except Exception, e: + except Exception as e: XSLogFailure('Device failed to unmount', e) self.pluggedVBD = False @@ -364,17 +364,17 @@ def __init__(self, inVDI, inMode = None): if status != 0: try: self.Unmount() - except Exception, e: + except Exception as e: XSLogFailure('Device failed to unmount', e) output += '\n'+self.mountDev self.HandleMountFailure(status, output.split("\n")) self.mountedVDI = True XSLog('Mounted '+self.mountDev + ' on ' + self.mountPoint + ' mode ' + self.mode) - except Exception, e: + except Exception as e: try: self.Unmount() - except Exception, e: + except Exception as e: XSLogFailure('Device failed to unmount', e) raise e @@ -466,7 +466,7 @@ def SRList(cls, inMode = None, inCapabilities = None): dataSR['opaqueref'] = sr.HotOpaqueRef().OpaqueRef() retVal.append( Struct(name = name, sr = dataSR) ) - retVal.sort(lambda x, y : cmp(x.name, y.name)) + retVal.sort(key=lambda data: data.name) return retVal diff --git a/XSConsoleDialogueBases.py b/XSConsoleDialogueBases.py index a6d989a..6211da0 100644 --- a/XSConsoleDialogueBases.py +++ b/XSConsoleDialogueBases.py @@ -43,11 +43,11 @@ def Title(self): return self.title def Destroy(self): - for pane in self.panes.values(): + for pane in list(self.panes.values()): pane.Delete() def Render(self): - for pane in self.panes.values(): + for pane in list(self.panes.values()): pane.Render() def UpdateFields(self): @@ -55,13 +55,13 @@ def UpdateFields(self): def NeedsCursor(self): retVal = False - for pane in self.panes.values(): + for pane in list(self.panes.values()): if pane.NeedsCursor(): retVal = True return retVal def CursorOff(self): - for pane in self.panes.values(): + for pane in list(self.panes.values()): pane.CursorOff() def Reset(self): @@ -204,7 +204,7 @@ def HandleKey(self, inKey): else: Layout.Inst().PushDialogue(InfoDialogue( Lang('Login Successful'))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang('Login Failed: ')+Lang(e))) Data.Inst().Update() @@ -401,7 +401,7 @@ def HandleKeyUSBNOTFORMATTED(self, inKey): try: FileUtils.USBFormat(self.vdi) self.HandleDevice() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Formatting Failed"), Lang(e))) handled = True @@ -425,7 +425,7 @@ def HandleKeyCUSTOM(self, inKey): FileUtils.AssertSafeLeafname(inputValues['filename']) self.filename = inputValues['filename'] self.ChangeState('CONFIRM') - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue(Lang(e))) elif pane.CurrentInput().HandleKey(inKey): @@ -477,7 +477,7 @@ def HandleDevice(self): except USBNotMountable: Layout.Inst().PopDialogue() self.ChangeState('USBNOTMOUNTABLE') - except Exception, e: + except Exception as e: try: self.PreExitActions() except Exception: @@ -542,7 +542,7 @@ def HandleKey(self, inKey): Layout.Inst().DoUpdate() title, info = self.HandleCommit(self.Pane().GetFieldValues()) Layout.Inst().PushDialogue(InfoDialogue( title, info)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang('Failed: ')+Lang(e))) elif inKey == 'KEY_TAB': pane.ActivateNextInput() @@ -651,7 +651,7 @@ def UpdateFieldsINITIAL(self): durationSecs = self.task.DurationSecs() elapsedStr = TimeUtils.DurationString(durationSecs) - except Exception, e: + except Exception as e: progressStr = Lang('') elapsedStr = Lang('') @@ -677,7 +677,7 @@ def UpdateFieldsCANCEL(self): durationSecs = self.task.DurationSecs() elapsedStr = TimeUtils.DurationString(durationSecs) - except Exception, e: + except Exception as e: progressStr = Lang('') elapsedStr = Lang('') @@ -702,7 +702,7 @@ def UpdateFieldsCOMPLETE(self): durationSecs = self.task.DurationSecs() elapsedStr = TimeUtils.DurationString(durationSecs) - except Exception, e: + except Exception as e: elapsedStr = Lang(e) pane.AddWrappedTextField(Lang('Time', 16) + elapsedStr) diff --git a/XSConsoleDialoguePane.py b/XSConsoleDialoguePane.py index a85ef26..88427da 100644 --- a/XSConsoleDialoguePane.py +++ b/XSConsoleDialoguePane.py @@ -57,8 +57,8 @@ def Update(self, inArranger): self.xSize = min(inArranger.XBounds(), self.parent.XSize() - self.SHRINKVALUE) self.xSize = (self.xSize + 1) & ~1 # make xSize even self.ySize = min(inArranger.YBounds(), self.parent.YSize() - self.SHRINKVALUE) - self.xPos = self.parent.XPos() + (self.parent.XSize() - self.xSize) / 2 - self.yPos = self.parent.YPos() + (self.parent.YSize() - self.ySize) / 2 + self.xPos = self.parent.XPos() + (self.parent.XSize() - self.xSize) // 2 + self.yPos = self.parent.YPos() + (self.parent.YSize() - self.ySize) // 2 class DialoguePane: def __init__(self, inParent = None, inSizer = None): diff --git a/XSConsoleFields.py b/XSConsoleFields.py index 6ed2b4f..aac9593 100644 --- a/XSConsoleFields.py +++ b/XSConsoleFields.py @@ -181,7 +181,7 @@ def Render(self, inPane, inXPos, inYPos): yPos = inYPos for line in self.wrappedText: if self.centred: - offset = (self.wrappedWidth - len(line)) / 2 + offset = (self.wrappedWidth - len(line)) // 2 inPane.AddText(line, inXPos+offset, yPos, self.colour) else: inPane.AddText(line, inXPos, yPos, self.colour) @@ -276,7 +276,7 @@ def InputFieldAdd(self, inTag, inField): def GetFieldValues(self): retVal = {} - for key, field in self.inputTags.iteritems(): + for key, field in self.inputTags.items(): retVal[key] = field.Content() return retVal diff --git a/XSConsoleHotData.py b/XSConsoleHotData.py index 14e2a60..39a5de3 100644 --- a/XSConsoleHotData.py +++ b/XSConsoleHotData.py @@ -15,7 +15,7 @@ import XenAPI -import commands, re, shutil, sys, socket +import subprocess, re, shutil, sys, socket from pprint import pprint from XSConsoleAuth import * @@ -61,9 +61,9 @@ def __getattr__(self, inName): def __iter__(self): iterData = HotData.Inst().GetData(self.name, {}, self.refs) - if isinstance(iterData, types.DictType): - self.iterKeys = iterData.keys() - elif isinstance(iterData, (types.ListType, types.TupleType)): + if isinstance(iterData, dict): + self.iterKeys = list(iterData.keys()) + elif isinstance(iterData, (list, tuple)): self.iterKeys = iterData[:] # [:] copy is necessary else: raise Exception(Lang("Cannot iterate over type '")+str(type(iterData))+"'") @@ -71,7 +71,7 @@ def __iter__(self): # This method will hide fields called 'next' in the xapi database. If any appear, __iter__ will need to # return a new object type and this method will need to be moved into that - def next(self): + def __next__(self): if len(self.iterKeys) <= 0: raise StopIteration retVal = HotAccessor(self.name[:], self.refs[:]) # [:] copies the array @@ -80,7 +80,7 @@ def next(self): def __getitem__(self, inParam): # These are square brackets selecting a particular item from a dict using its OpaqueRef - if not isinstance(inParam, (types.IntType, HotOpaqueRef)): + if not isinstance(inParam, (int, HotOpaqueRef)): raise Exception('Use of HotAccessor[param] requires param of type int or HotOpaqueRef, but got '+str(type(inParam))) retVal = HotAccessor(self.name[:], self.refs[:]) retVal.refs[-1] = inParam @@ -134,7 +134,7 @@ def Fetch(self, inName, inRef): fetcher = self.fetchers[inName] timeNow = time.time() # If inRef is an array index, the result can't be cached - if not isinstance(inRef, types.IntType) and cacheEntry is not None and timeNow - cacheEntry.timestamp < fetcher.lifetimeSecs: + if not isinstance(inRef, int) and cacheEntry is not None and timeNow - cacheEntry.timestamp < fetcher.lifetimeSecs: retVal = cacheEntry.value else: try: @@ -172,7 +172,7 @@ def GetData(self, inNames, inDefault, inRefs): # We have a fetcher for this element, so use it # Handle the case where itemRef is a dictionary containing the key/value pair ( current name : HotOpaqueRef ) - if isinstance(itemRef, types.DictType) and name in itemRef and isinstance(itemRef[name], HotOpaqueRef): + if isinstance(itemRef, dict) and name in itemRef and isinstance(itemRef[name], HotOpaqueRef): # This is a subitem with an OpaqueRef supplied by xapi, so fetch the obect it's referring to itemRef = self.Fetch(name, itemRef[name]) else: @@ -189,14 +189,14 @@ def GetData(self, inNames, inDefault, inRefs): itemRef = itemRef[name] # Allow to throw if element not present # Handle integer references as list indices - if isinstance(currentRef, types.IntType): - if not isinstance(itemRef, (types.ListType, types.TupleType)): + if isinstance(currentRef, int): + if not isinstance(itemRef, (list, tuple)): raise Exception("List index supplied but element '"+'.'.join(inNames)+"' is not a list") if inRefs[i] >= len(itemRef) or currentRef < -len(itemRef): raise Exception("List index "+str(currentRef)+" out of range in '"+'.'.join(inNames)+"'") itemRef = itemRef[currentRef] return itemRef - except Exception, e: + except Exception as e: # Data not present/fetchable, so return the default value return FirstValue(inDefault, None) @@ -236,7 +236,7 @@ def FetchGuestVM(self, inOpaqueRef): retVal = self.FetchVM(inOpaqueRef) else: retVal = {} - for key, value in self.vm().iteritems(): + for key, value in self.vm().items(): if not value.get('is_a_template', False) and not value.get('is_control_domain', False): retVal[key] = value return retVal @@ -253,7 +253,7 @@ def LocalConverter(inCPU): else: cpus = self.Session().xenapi.host_cpu.get_all_records() retVal = {} - for key, cpu in cpus.iteritems(): + for key, cpu in cpus.items(): cpu = LocalConverter(cpu) retVal[HotOpaqueRef(key, 'host_cpu')] = cpu return retVal @@ -265,7 +265,7 @@ def FetchGuestVMDerived(self, inOpaqueRef): running = 0 suspended = 0 - for key, vm in self.guest_vm().iteritems(): + for key, vm in self.guest_vm().items(): powerState = vm.get('power_state', '').lower() if powerState.startswith('halted'): halted += 1 @@ -327,7 +327,7 @@ def LocalConverter(inHost): else: hosts = self.Session().xenapi.host.get_all_records() retVal = {} - for key, host in hosts.iteritems(): + for key, host in hosts.items(): host = LocalConverter(host) retVal[HotOpaqueRef(key, 'host')] = host return retVal @@ -356,7 +356,7 @@ def LocalConverter(inPBD): else: pbds = self.Session().xenapi.PBD.get_all_records() retVal = {} - for key, pbd in pbds.iteritems(): + for key, pbd in pbds.items(): pbd = LocalConverter(pbd) retVal[HotOpaqueRef(key, 'pbd')] = pbd return retVal @@ -376,7 +376,7 @@ def LocalConverter(inPool): else: pools = self.Session().xenapi.pool.get_all_records() retVal = {} - for key, pool in pools.iteritems(): + for key, pool in pools.items(): pool = LocalConverter(pool) retVal[HotOpaqueRef(key, 'pool')] = pool return retVal @@ -394,7 +394,7 @@ def LocalConverter(inSR): else: srs = self.Session().xenapi.SR.get_all_records() retVal = {} - for key, sr in srs.iteritems(): + for key, sr in srs.items(): sr = LocalConverter(sr) retVal[HotOpaqueRef(key, 'sr')] = sr return retVal @@ -439,7 +439,7 @@ def LocalConverter(inVM): else: vms = self.Session().xenapi.VM.get_all_records() retVal = {} - for key, vm in vms.iteritems(): + for key, vm in vms.items(): vm = LocalConverter(vm) retVal[HotOpaqueRef(key, 'vm')] = vm return retVal @@ -449,32 +449,32 @@ def ConvertOpaqueRefs(cls, *inArgs, **inKeywords): if len(inArgs) != 1: raise Exception('ConvertOpaqueRef requires a dictionary object as the first argument') ioObj = inArgs[0] - for keyword, value in inKeywords.iteritems(): + for keyword, value in inKeywords.items(): obj = ioObj.get(keyword, None) if obj is not None: if isinstance(obj, str): ioObj[keyword] = HotOpaqueRef(obj, value) - elif isinstance(obj, types.ListType): + elif isinstance(obj, list): ioObj[keyword] = [ HotOpaqueRef(x, value) for x in obj ] - elif isinstance(obj, types.DictType): + elif isinstance(obj, dict): result = {} - for key, item in obj.iteritems(): + for key, item in obj.items(): result[ HotOpaqueRef(key, value) ] = item ioObj[keyword] = result if Auth.Inst().IsTestMode(): # Tell the caller what they've missed, when in test mode - for key,value in ioObj.iteritems(): + for key,value in ioObj.items(): if isinstance(value, str) and value.startswith('OpaqueRef'): - print('Missed OpaqueRef string in HotData item: '+key) - elif isinstance(value, types.ListType): + print(('Missed OpaqueRef string in HotData item: '+key)) + elif isinstance(value, list): for item in value: if isinstance(item, str) and item.startswith('OpaqueRef'): - print('Missed OpaqueRef List in HotData item: '+key) + print(('Missed OpaqueRef List in HotData item: '+key)) break - elif isinstance(value, types.DictType): - for item in value.keys(): + elif isinstance(value, dict): + for item in list(value.keys()): if isinstance(item, str) and item.startswith('OpaqueRef'): - print('Missed OpaqueRef Dict in HotData item: '+key) + print(('Missed OpaqueRef Dict in HotData item: '+key)) break return ioObj @@ -485,5 +485,5 @@ def Session(self): return self.session def Dump(self): - print "Contents of HotData cache:" + print("Contents of HotData cache:") pprint(self.data) diff --git a/XSConsoleImporter.py b/XSConsoleImporter.py index a45984d..16eb260 100644 --- a/XSConsoleImporter.py +++ b/XSConsoleImporter.py @@ -47,7 +47,7 @@ def ImportAbsDir(cls, inDir): # Import using variable as module name (fileObj, pathName, description) = imp.find_module(importName, [root]) imp.load_module(importName, fileObj, pathName, description) - except Exception, e: + except Exception as e: try: XSLogError(*traceback.format_tb(sys.exc_info()[2])) except: pass try: XSLogError("*** PlugIn '"+importName+"' failed to load: "+str(e)) @@ -113,12 +113,8 @@ def ActivateNamedPlugIn(cls, inName, *inParams): @classmethod def CallReadyHandlers(cls): # Sort plugins in descending priority order with a default of 1000 - def CmpPlugin(x, y): - return cmp(y.get('readyhandlerpriority', 1000), - x.get('readyhandlerpriority', 1000)) - - plugins = cls.plugIns.values() - plugins.sort(CmpPlugin) + plugins = list(cls.plugIns.values()) + plugins.sort(key=lambda p: p.get('readyhandlerpriority', 1000), reverse=True) for plugin in plugins: handler = plugin.get('readyhandler', None) @@ -128,7 +124,7 @@ def CmpPlugin(x, y): @classmethod def GetResource(cls, inName): # Don't use this until all of the PlugIns have had a chance to register retVal = None - for resource in cls.resources.values(): + for resource in list(cls.resources.values()): item = resource.get(inName, None) if item is not None: retVal = item @@ -147,7 +143,7 @@ def GetResourceOrThrow(cls, inName): # Don't use this until all of the PlugIns h def BuildRootMenu(cls, inParent): retVal = RootMenu(inParent) - for name, entries in cls.menuEntries.iteritems(): + for name, entries in cls.menuEntries.items(): for entry in entries: # Create the menu that this item is in retVal.CreateMenuIfNotPresent(name) @@ -159,7 +155,7 @@ def BuildRootMenu(cls, inParent): choiceDef.StatusUpdateHandlerSet(entry.get('statusupdatehandler', None)) retVal.AddChoice(name, choiceDef, entry.get('menupriority', None)) - for entry in cls.plugIns.values(): + for entry in list(cls.plugIns.values()): menuName = entry.get('menuname', None) if menuName is not None: choiceDef = ChoiceDef(entry['menutext'], entry.get('activatehandler', None), entry.get('statushandler', None)) @@ -178,10 +174,10 @@ def RegenerateMenu(cls, inName, inMenu): @classmethod def Dump(cls): - print "Contents of PlugIn registry:" + print("Contents of PlugIn registry:") pprint(cls.plugIns) - print "\nRegistered menu entries:" + print("\nRegistered menu entries:") pprint(cls.menuEntries) - print "\nRegistered resources:" + print("\nRegistered resources:") pprint(cls.resources) diff --git a/XSConsoleLang.py b/XSConsoleLang.py index 4ae8bac..f47e239 100644 --- a/XSConsoleLang.py +++ b/XSConsoleLang.py @@ -25,20 +25,20 @@ def Lang(inLabel, inPad = 0): if inPad > 0: retStr = retStr.ljust(inPad, ' ') return retStr - + class Language: instance = None stringHook = None errorHook = None errorLoggingHook = None - + def __init__(self): self.brandingMap = Config.Inst().BrandingMap() - + @classmethod def SetStringHook(cls, inHook): cls.stringHook = inHook - + @classmethod def SetErrorHook(cls, inHook): cls.errorHook = inHook @@ -52,7 +52,7 @@ def Inst(self): if self.instance is None: self.instance = Language() return self.instance - + @classmethod def Quantity(cls, inText, inNumber): if inNumber == 1: @@ -82,15 +82,15 @@ def ToString(cls, inLabel): elif isinstance(inLabel, Exception): exn_strings = [] for arg in inLabel.args: - if isinstance(arg, unicode): - exn_strings.append(arg.encode('utf-8')) + if isinstance(arg, bytes): + exn_strings.append(arg.decode('utf-8')) else: exn_strings.append(str(arg)) retVal = str(tuple(exn_strings)) cls.LogError(retVal) else: - if isinstance(inLabel, unicode): - inLabel = inLabel.encode('utf-8') + if isinstance(inLabel, bytes): + inLabel = inLabel.decode('utf-8') retVal = inLabel if cls.stringHook is not None: cls.stringHook(retVal) @@ -112,19 +112,19 @@ def ReflowText(cls, inText, inWidth): lineLength = inWidth else: lineLength = spacePos - + thisLine = text[:lineLength] thisLine = thisLine.replace("\t", " ") # Tab is used as a non-breaking space thisLine = thisLine.replace("\r", "RET") # Debugging thisLine = thisLine.strip() # Remove leading whitespace (generally the second space in a double space) if len(thisLine) > 0 or retPos != -1: # Only add blank lines if they follow a return retArray.append(thisLine) - + if spacePos == -1: text = text[lineLength:] # Split at non-space/return, so keep else: text = text[lineLength+1:] # Split at space or return so discard - + return retArray def Branding(self, inText): diff --git a/XSConsoleLayout.py b/XSConsoleLayout.py index 28a2d2c..7bbcd9c 100644 --- a/XSConsoleLayout.py +++ b/XSConsoleLayout.py @@ -122,8 +122,8 @@ def WriteParentOffset(self, inParent): # Centralise subsequent windows inParent.OffsetSet( - (inParent.XSize() - self.APP_XSIZE) / 2, - (inParent.YSize() - self.APP_YSIZE) / 2) + (inParent.XSize() - self.APP_XSIZE) // 2, + (inParent.YSize() - self.APP_YSIZE) // 2) def Create(self): self.windows.append(CursesWindow(0,1,self.APP_XSIZE, self.APP_YSIZE-1, self.parent)) # MainWindow diff --git a/XSConsoleMenus.py b/XSConsoleMenus.py index d8248fe..8af2f03 100644 --- a/XSConsoleMenus.py +++ b/XSConsoleMenus.py @@ -67,7 +67,7 @@ def AddChoiceDef(self, inChoiceDef, inPriority = None): inChoiceDef.priority = priority # FIXME (modifies input parameter) self.choiceDefs.append(inChoiceDef) - self.choiceDefs.sort(lambda x, y : cmp(x.priority, y.priority)) + self.choiceDefs.sort(key=lambda c: c.priority) def AddChoice(self, name, onAction = None, onEnter = None, priority = None, statusUpdateHandler = None, handle = None): choiceDef = ChoiceDef(name, onAction, onEnter, priority, statusUpdateHandler, handle) @@ -181,13 +181,13 @@ def ChangeMenu(self, inKey): def Reset(self): self.currentKey = 'MENU_ROOT' - for menu in self.menus.values(): + for menu in list(self.menus.values()): menu.CurrentChoiceSet(0) self.CurrentMenu().HandleEnter() def AddChoice(self, inMenuName, inChoiceDef, inPriority = None): - if not self.menus.has_key(inMenuName): + if inMenuName not in self.menus: raise Exception(Lang("Unknown menu '")+inMenuName+"'") self.menus[inMenuName].AddChoiceDef(inChoiceDef, inPriority) diff --git a/XSConsoleMetrics.py b/XSConsoleMetrics.py index 6f005d9..8cf4d8a 100644 --- a/XSConsoleMetrics.py +++ b/XSConsoleMetrics.py @@ -14,7 +14,7 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. import XenAPI -import urllib +import urllib.request, urllib.parse, urllib.error import xml.dom.minidom from XSConsoleAuth import * @@ -42,7 +42,7 @@ def LocalHostMetrics(self): retVal = {} hostPrefix = r'AVERAGE:host:'+self.thisHostUUID cpuRE = re.compile(hostPrefix+r':cpu[0-9]+$') - cpuValues = [ float(v) for k, v in self.data.iteritems() if cpuRE.match(k) ] + cpuValues = [ float(v) for k, v in self.data.items() if cpuRE.match(k) ] retVal['numcpus'] = len(cpuValues) if len(cpuValues) == 0: retVal['cpuusage'] = None @@ -51,12 +51,12 @@ def LocalHostMetrics(self): try: retVal['memory_total'] = float(self.data[hostPrefix +':memory_total_kib']) * 1024.0 - except Exception, e: + except Exception as e: retVal['memory_total'] = None try: retVal['memory_free'] = float(self.data[hostPrefix +':memory_free_kib']) * 1024.0 - except Exception, e: + except Exception as e: retVal['memory_free'] = None return retVal @@ -67,7 +67,7 @@ def VMMetrics(self, inUUID): vmPrefix = r'AVERAGE:vm:' + inUUID cpuRE = re.compile(vmPrefix+r':cpu[0-9]+$') - cpuValues = [ float(v) for k, v in self.data.iteritems() if cpuRE.match(k) ] + cpuValues = [ float(v) for k, v in self.data.items() if cpuRE.match(k) ] retVal['numcpus'] = len(cpuValues) if len(cpuValues) == 0: retVal['cpuusage'] = None @@ -76,12 +76,12 @@ def VMMetrics(self, inUUID): try: retVal['memory_total'] = float(self.data[vmPrefix +':memory']) # Not scaled - except Exception, e: + except Exception as e: retVal['memory_total'] = None try: retVal['memory_free'] = float(self.data[vmPrefix +':memory_internal_free']) * 1024.0 # Value is in kiB - except Exception, e: + except Exception as e: retVal['memory_free'] = None return retVal @@ -138,7 +138,7 @@ def FetchData(self): httpRequest = 'http://localhost/rrd_updates?session_id=%s&start=%s&host=true' % (sessionID, int(time.time()) - self.SNAPSHOT_SECS) - socket = urllib.URLopener().open(httpRequest) + socket = urllib.request.URLopener().open(httpRequest) try: content = socket.read() finally: diff --git a/XSConsoleRemoteTest.py b/XSConsoleRemoteTest.py index ab294a9..2f39506 100644 --- a/XSConsoleRemoteTest.py +++ b/XSConsoleRemoteTest.py @@ -13,7 +13,7 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. -import os, socket, xmlrpclib +import os, socket, xmlrpc.client from XSConsoleBases import * from XSConsoleImporter import * @@ -21,19 +21,19 @@ from XSConsoleLog import * from XSConsoleLayout import * -import SocketServer -import SimpleXMLRPCServer +import socketserver +import xmlrpc.server -class UnixSimpleXMLRPCRequestHandler(SimpleXMLRPCServer.SimpleXMLRPCRequestHandler): +class UnixSimpleXMLRPCRequestHandler(xmlrpc.server.SimpleXMLRPCRequestHandler): # Python 2.7's SimpleXMLRPCRequestHandler enables Nagle's algorithm by default # which fails because we're working with Unix domain sockets so disable it. disable_nagle_algorithm = False -class UDSXMLRPCServer(SocketServer.UnixStreamServer, SimpleXMLRPCServer.SimpleXMLRPCDispatcher): +class UDSXMLRPCServer(socketserver.UnixStreamServer, xmlrpc.server.SimpleXMLRPCDispatcher): def __init__(self, inAddr, inRequestHandler = None): self.logRequests = False - SimpleXMLRPCServer.SimpleXMLRPCDispatcher.__init__(self) - SocketServer.UnixStreamServer.__init__(self, inAddr, + xmlrpc.server.SimpleXMLRPCDispatcher.__init__(self) + socketserver.UnixStreamServer.__init__(self, inAddr, FirstValue(inRequestHandler, UnixSimpleXMLRPCRequestHandler)) def handle_request(self): @@ -108,7 +108,7 @@ def ErrorString(self, inException = None): for i, pane in enumerate(snapshot): for line in pane: retVal += 'Pane '+str(i) + ':' + line + '\n' - except Exception, e: + except Exception as e: retVal += 'Failed: '+Lang(e) if len(self.errors) > 0: retVal += "\n\nExceptions process by Lang()\n\n" + "\n".join(self.errors) @@ -121,15 +121,15 @@ def ErrorString(self, inException = None): def WrapProcedure(self, inProc): # Any return value of inProc is discarded try: inProc() - except Exception, e: - raise xmlrpclib.Fault(1, self.ErrorString(e)) + except Exception as e: + raise xmlrpc.client.Fault(1, self.ErrorString(e)) return None def WrapFunction(self, inFunc): # inFunc returns a value try: retVal = inFunc() - except Exception, e: - raise xmlrpclib.Fault(1, self.ErrorString(e)) + except Exception as e: + raise xmlrpc.client.Fault(1, self.ErrorString(e)) return retVal def StandardReturn(self, inInfix = None): @@ -193,7 +193,7 @@ def HandleXMLRPCVerify(self, inString): result = line break if result is None: - raise xmlrpclib.Fault(1, self.ErrorString()+"\n\nSearch string '"+inString+"' not found.") + raise xmlrpc.client.Fault(1, self.ErrorString()+"\n\nSearch string '"+inString+"' not found.") return self.StandardReturn("found '"+result+"'") def HandleXMLRPCActivate(self, inName): @@ -250,7 +250,7 @@ def HandleXMLRPCAssertFailure(self): """ self.params = ['assertfailure'] if len(self.errors) == 0: - raise xmlrpclib.Fault(1, self.ErrorString()) + raise xmlrpc.client.Fault(1, self.ErrorString()) return self.StandardReturn() def HandleXMLRPCAssertSuccess(self): @@ -261,7 +261,7 @@ def HandleXMLRPCAssertSuccess(self): """ self.params = ['assertsuccess'] if len(self.errors) > 0: - raise xmlrpclib.Fault(1, self.ErrorString()) + raise xmlrpc.client.Fault(1, self.ErrorString()) return self.StandardReturn() class NullRemoteTest: diff --git a/XSConsoleRootDialogue.py b/XSConsoleRootDialogue.py index 80c37d0..708c703 100644 --- a/XSConsoleRootDialogue.py +++ b/XSConsoleRootDialogue.py @@ -67,7 +67,7 @@ def UpdateFields(self): else: raise Exception(Lang("Missing status handler")) - except Exception, e: + except Exception as e: statusPane.ResetFields() statusPane.ResetPosition() statusPane.AddTitleField(Lang("Information not available")) diff --git a/XSConsoleState.py b/XSConsoleState.py index 291bedb..c5d479c 100644 --- a/XSConsoleState.py +++ b/XSConsoleState.py @@ -59,7 +59,7 @@ def Inst(cls): # Version mismatch - don't use the state information cls.instance = None XSLog('State file version mismatch - discarding') - except Exception, e: + except Exception as e: cls.instance = None if cls.instance is None: @@ -136,7 +136,7 @@ def SaveIfRequired(self): self.MakeSane() try: if not os.path.isdir(self.savePath): - os.mkdir(self.savePath, 0700) + os.mkdir(self.savePath, 0o700) saveFile = open(self.SaveFilename(), "w") pickler = pickle.Pickler(saveFile) @@ -144,7 +144,7 @@ def SaveIfRequired(self): pickler.dump(self) saveFile.close() XSLog('Saved state file') - except Exception, e: + except Exception as e: XSLogFailure('Failed to save state file', e) diff --git a/XSConsoleTask.py b/XSConsoleTask.py index 9e8e1ee..9766b96 100644 --- a/XSConsoleTask.py +++ b/XSConsoleTask.py @@ -144,7 +144,7 @@ def Create(self, inProc): def GarbageCollect(self): # This may be expensive as it must fetch status from xapi for each incomplete task deleteKeys = [] - for key, value in self.taskList.iteritems(): + for key, value in self.taskList.items(): # Forget tasks that have of duration of greater than one day value.Status() if value.Completed() or value.DurationSecs() > 86400: diff --git a/XSConsoleTerm.py b/XSConsoleTerm.py index 2c6f7ab..ffc001b 100644 --- a/XSConsoleTerm.py +++ b/XSConsoleTerm.py @@ -64,7 +64,7 @@ def Enter(self): # Testing - dump data and exit Data.Inst().Dump() Importer.Dump() - for key, value in HotData.Inst().guest_vm().iteritems(): + for key, value in HotData.Inst().guest_vm().items(): localhost = HotAccessor().local_host() vm = HotData.Inst().vm[key] vm.metrics() @@ -139,16 +139,16 @@ def Enter(self): os.system(self.layout.ExitCommand()) Data.Inst().Update() # Pick up changes caused by the subshell command - except KeyboardInterrupt, e: # Catch Ctrl-C + except KeyboardInterrupt as e: # Catch Ctrl-C XSLog('Resetting due to Ctrl-C') Data.Reset() sys.stderr.write("\033[H\033[J"+Lang("Resetting...")) # Clear screen and print banner try: time.sleep(0.5) # Prevent flicker - except Exception, e: + except Exception as e: pass # Catch repeated Ctrl-C - except Exception, e: + except Exception as e: sys.stderr.write(Lang(e)+"\n") doQuit = True raise @@ -212,7 +212,7 @@ def MainLoop(self): else: gotKey = self.layout.Window(Layout.WIN_MAIN).GetKey() - except Exception, e: + except Exception as e: gotKey = None # Catch timeout if gotKey == "\011": gotKey = "KEY_TAB" @@ -257,7 +257,7 @@ def MainLoop(self): try: self.HandleKeypress(gotKey) - except Exception, e: + except Exception as e: if Auth.Inst().IsTestMode(): raise message = Lang(e) # Also logs the error diff --git a/XSConsoleUtils.py b/XSConsoleUtils.py index f5a3ad1..843329a 100644 --- a/XSConsoleUtils.py +++ b/XSConsoleUtils.py @@ -49,58 +49,59 @@ def __init__(self, *inParams): self.stdout = [] self.stderr = [] self.called = False - + def _NewPipe(self, *inParams): - if len(inParams) == 1 and isinstance(inParams, (types.ListType, types.TupleType)): + if len(inParams) == 1 and isinstance(inParams, (list, tuple)): params = inParams[0] else: params = inParams - + self.pipe = subprocess.Popen(params, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, close_fds=True) self.called = False - + def Stdout(self): if not self.called: self.Call() return self.stdout - + def Stderr(self): if not self.called: self.Call() return self.stderr - + def AllOutput(self): if not self.called: self.Call() return self.stdout + self.stderr - + def Communicate(self, inInput = None): if self.called: raise Exception("ShellPipe called more than once") self.called = True while True: try: - if isinstance(inInput, (types.ListType, types.TupleType)): + if isinstance(inInput, (list, tuple)): stdout, stderr = self.pipe.communicate("\n".join(inInput)) else: stdout, stderr = self.pipe.communicate(inInput) - + self.stdout += stdout.splitlines() self.stderr += stderr.splitlines() break - except IOError, e: + except IOError as e: if e.errno != errno.EINTR: # Loop if EINTR raise # Other exceptions propagate to the caller - + def CallRC(self, inInput = None): # Raise exception or return the return code self.Communicate(inInput) return self.pipe.returncode - + def Call(self, inInput = None): # Raise exception on failure self.Communicate(inInput) if self.pipe.returncode != 0: @@ -111,14 +112,14 @@ def Call(self, inInput = None): # Raise exception on failure else: raise Exception("Unknown failure") return self - + def Chain(self, *inParams): if not self.called: self.Call() self._NewPipe(*inParams) self.Call() return self - + def Pipe(self, *inParams): if not self.called: self.Call() @@ -135,7 +136,7 @@ def MakeSafeParam(cls, inParam): if not re.match(r'[-A-Za-z0-9/._~:@]*$', inParam): raise Exception("Invalid characters in parameter '"+inParam+"'") return inParam - + @classmethod def WaitOnPipe(cls, inPipe): # Wait on a popen2 pipe, handling Interrupted System Call exceptions @@ -143,7 +144,7 @@ def WaitOnPipe(cls, inPipe): try: inPipe.wait() break - except IOError, e: + except IOError as e: if e.errno != errno.EINTR: # Loop if EINTR raise @@ -154,7 +155,7 @@ class TimeUtils: @staticmethod def AlarmHandler(inSigNum, inStackFrame): raise TimeException("Operation timed out") - + @classmethod def TimeoutWrapper(cls, inCallable, inTimeout): oldHandler = signal.signal(signal.SIGALRM, TimeUtils.AlarmHandler) @@ -164,11 +165,11 @@ def TimeoutWrapper(cls, inCallable, inTimeout): finally: signal.alarm(0) signal.signal(signal.SIGALRM, oldHandler) - + @classmethod def DurationString(cls, inSecs): secs = max(0, int(inSecs)) - + hours = int(secs / 3600) secs -= hours * 3600 mins = int(secs / 60) @@ -178,7 +179,7 @@ def DurationString(cls, inSecs): else: retVal = "%d:%2.2d" % (mins, secs) return retVal - + @classmethod def DateTimeToSecs(cls, inDateTime): structTime = time.strptime(inDateTime.value, '%Y%m%dT%H:%M:%SZ') @@ -186,26 +187,26 @@ def DateTimeToSecs(cls, inDateTime): if retVal <= 3601.0: # Handle the effect of daylight savings on start of epoch retVal = 0.0 return retVal - + class IPUtils: @classmethod def ValidateIP(cls, text): rc = re.match("^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$", text) if not rc: return False - ints = map(int, rc.groups()) + ints = list(map(int, rc.groups())) largest = 0 for i in ints: if i > 255: return False largest = max(largest, i) - if largest is 0: return False + if largest == 0: return False return True - + @classmethod def ValidateNetmask(cls, text): rc = re.match("^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$", text) if not rc: return False - ints = map(int, rc.groups()) + ints = list(map(int, rc.groups())) for i in ints: if i > 255: return False @@ -229,7 +230,7 @@ def AssertValidHostname(cls, inName): if not re.match(r'[0-9A-Za-z]([-0-9A-Za-z]{0,61}[0-9A-Za-z]|)$', inName): raise Exception(Lang('Invalid hostname')) return inName - + @classmethod def AssertValidNetworkName(cls, inName): # Also allow FQDN-style names @@ -261,7 +262,7 @@ def AssertValidNFSPathName(cls, inName): for subName in splitNames[1:]: cls.AssertValidNFSDirectoryName(subName) return inName - + @classmethod def AssertValidCIFSPathName(cls, inName): splitNames = inName.split('\\') @@ -277,7 +278,7 @@ def BinarySizeString(cls, inBytes, inInFix = None): else: inFix = FirstValue(inInFix, '') bytes = int(inBytes) - + if bytes is None or bytes < 0: retVal = Lang('') elif bytes >= 1073741824: # 1GiB @@ -320,7 +321,7 @@ def DecimalSizeString(cls, inBytes, inPrefix = None): @classmethod def MemorySizeString(cls, inBytes): return cls.BinarySizeString(inBytes) - + @classmethod def SRSizeString(cls, inBytes): return cls.BinarySizeString(inBytes) @@ -328,4 +329,4 @@ def SRSizeString(cls, inBytes): @classmethod def DiskSizeString(cls, inBytes): return cls.BinarySizeString(inBytes)+' ('+cls.DecimalSizeString(inBytes)+')' - + diff --git a/plugins-base/XSFeatureChangePassword.py b/plugins-base/XSFeatureChangePassword.py index df28468..3f9c6cf 100644 --- a/plugins-base/XSFeatureChangePassword.py +++ b/plugins-base/XSFeatureChangePassword.py @@ -76,7 +76,7 @@ def HandleKey(self, inKey): Auth.Inst().ChangePassword(inputValues.get('oldpassword', ''), inputValues['newpassword1']) - except Exception, e: + except Exception as e: if self.isPasswordSet: # Only remove the dialogue if this isn't the initial password set (which needs to succeed) Layout.Inst().PopDialogue() diff --git a/plugins-base/XSFeatureChangeTimeout.py b/plugins-base/XSFeatureChangeTimeout.py index 912f194..f18a4c7 100644 --- a/plugins-base/XSFeatureChangeTimeout.py +++ b/plugins-base/XSFeatureChangeTimeout.py @@ -29,7 +29,7 @@ def __init__(self): def HandleCommit(self, inValues): try: timeoutMinutes = int(inValues['timeout']) - except Exception, e: + except Exception as e: raise Exception("Invalid value - please supply a numeric value") Auth.Inst().TimeoutSecondsSet(timeoutMinutes * 60) diff --git a/plugins-base/XSFeatureCrashDumpSR.py b/plugins-base/XSFeatureCrashDumpSR.py index 353b0c5..44ddb08 100644 --- a/plugins-base/XSFeatureCrashDumpSR.py +++ b/plugins-base/XSFeatureCrashDumpSR.py @@ -37,7 +37,7 @@ def DoAction(self, inSR): Data.Inst().CrashDumpSRSet(inSR) Layout.Inst().PushDialogue(InfoDialogue( Lang('Configuration Successful'), Lang("Crash Dump SR set to '"+inSR['name_label']+"'"))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration failed: ")+str(e))) Data.Inst().Update() diff --git a/plugins-base/XSFeatureDNS.py b/plugins-base/XSFeatureDNS.py index 132b209..97b48c0 100644 --- a/plugins-base/XSFeatureDNS.py +++ b/plugins-base/XSFeatureDNS.py @@ -106,7 +106,7 @@ def HandleKeyADD(self, inKey): nameservers.append(inputValues['name']) data.NameserversSet(nameservers) self.Commit(Lang("DNS server")+" "+inputValues['name']+" "+Lang("added")) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang(e))) elif pane.CurrentInput().HandleKey(inKey): pass # Leave handled as True @@ -140,7 +140,7 @@ def HandleInitialChoice(self, inChoice): data.NameserversSet([]) self.Commit(Lang("All server entries deleted")) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Operation Failed"), Lang(e))) data.Update() @@ -160,7 +160,7 @@ def Commit(self, inMessage): try: data.SaveToResolveConf() Layout.Inst().PushDialogue(InfoDialogue( inMessage)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Update failed: ")+Lang(e))) data.Update() diff --git a/plugins-base/XSFeatureDRBackup.py b/plugins-base/XSFeatureDRBackup.py index b05ac49..c4ab9c7 100644 --- a/plugins-base/XSFeatureDRBackup.py +++ b/plugins-base/XSFeatureDRBackup.py @@ -51,7 +51,7 @@ def DoAction(self, inSR): Layout.Inst().PushDialogue(InfoDialogue(Lang("Backup Successful"), output)) else: raise Exception(output) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Metadata Backup failed: ")+Lang(e))) Data.Inst().Update() diff --git a/plugins-base/XSFeatureDRRestore.py b/plugins-base/XSFeatureDRRestore.py index 2cadde5..197a3ce 100644 --- a/plugins-base/XSFeatureDRRestore.py +++ b/plugins-base/XSFeatureDRRestore.py @@ -170,7 +170,7 @@ def DoAction(self, inSR): if status != 0: raise Exception("(%s,%s)" % (output,errput)) Layout.Inst().PushDialogue(DRRestoreSelection(output, vdi_uuid, sr_uuid)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Metadata Restore failed: ")+Lang(e))) Data.Inst().Update() diff --git a/plugins-base/XSFeatureEULA.py b/plugins-base/XSFeatureEULA.py index 15f5adf..1bfb0a8 100644 --- a/plugins-base/XSFeatureEULA.py +++ b/plugins-base/XSFeatureEULA.py @@ -32,13 +32,13 @@ def __init__(self, inFilename): contents = ''.join(file.readlines()) finally: file.close() - except Exception, e: + except Exception as e: contents = str(e) self.maxLine = 0 for line in contents.split('\n'): self.maxLine = max(self.maxLine, len(line)) - self.padding = ' ' * max(0, (xSize - 4 - self.maxLine) / 2) + self.padding = ' ' * max(0, (xSize - 4 - self.maxLine) // 2) self.text = Lang("End User License Agreement") self.info = contents diff --git a/plugins-base/XSFeatureHostCommon.py b/plugins-base/XSFeatureHostCommon.py index 9fecd68..38ea67b 100644 --- a/plugins-base/XSFeatureHostCommon.py +++ b/plugins-base/XSFeatureHostCommon.py @@ -27,7 +27,7 @@ class HostUtils: @classmethod def AllowedOperations(cls): - return cls.operationNames.keys() + return list(cls.operationNames.keys()) @classmethod def OtherConfigRemove(cls, inHostHandle, inName): diff --git a/plugins-base/XSFeatureHostEvacuate.py b/plugins-base/XSFeatureHostEvacuate.py index d654fe7..c90725c 100644 --- a/plugins-base/XSFeatureHostEvacuate.py +++ b/plugins-base/XSFeatureHostEvacuate.py @@ -182,7 +182,7 @@ def Commit(self): message = Lang('Please allow several seconds for the pool to propagate information about the new Master') Layout.Inst().PushDialogue(InfoDialogue(Lang("Host Successfully Entered Maintenance Mode"), message)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Enter Maintenance Mode Failed to Complete"), Lang(e))) else: try: @@ -191,7 +191,7 @@ def Commit(self): vmUtils = Importer.GetResource('VMUtils') vmUtils.ReinstateVMs(HotAccessor().local_host_ref(), self.evacuatedVMs) Layout.Inst().PushDialogue(InfoDialogue(Lang("Host Successfully Exited Maintenance Mode"))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Exit Maintenance Mode Failed"), Lang(e))) class XSFeatureHostEvacuate: diff --git a/plugins-base/XSFeatureHostInfo.py b/plugins-base/XSFeatureHostInfo.py index 754c683..c19721c 100644 --- a/plugins-base/XSFeatureHostInfo.py +++ b/plugins-base/XSFeatureHostInfo.py @@ -24,7 +24,7 @@ def StatusUpdateHandler(cls, inPane): inPane.AddTitleField("Host Performance Information") try: localHostMetrics = HotMetrics.Inst().LocalHostMetrics() - except Exception, e: + except Exception as e: XSLogFailure('LocalHostMetrics failed', e) localHostMetrics = {} @@ -32,7 +32,7 @@ def StatusUpdateHandler(cls, inPane): cpuUsage = localHostMetrics['cpuusage'] cpuUsage = max(0.0, min(1.0, cpuUsage)) cpuUsageStr = "%d%% of %d CPUs" % (int(cpuUsage * 100), localHostMetrics['numcpus']) - except Exception, e: + except Exception as e: cpuUsageStr = Lang('') try: @@ -43,7 +43,7 @@ def StatusUpdateHandler(cls, inPane): # Increase memory slightly to counteract metrics error totalMemory *= 1.001 memoryUsageStr = "%d%% of %s" % (int(memoryUsage * 100), SizeUtils.MemorySizeString(totalMemory)) - except Exception, e: + except Exception as e: memoryUsageStr = Lang('') inPane.AddStatusField(Lang("CPU Usage", 16), cpuUsageStr) diff --git a/plugins-base/XSFeatureInterface.py b/plugins-base/XSFeatureInterface.py index d36646b..5769f44 100644 --- a/plugins-base/XSFeatureInterface.py +++ b/plugins-base/XSFeatureInterface.py @@ -315,7 +315,7 @@ def HandleKeyPRECOMMIT(self, inKey): else: self.Complete() # Disabled management interface - except Exception, e: + except Exception as e: self.Complete(Lang("Configuration Failed: "+Lang(e))) else: @@ -337,7 +337,7 @@ def HandleKeyNAMELABEL(self, inKey): try: Data.Inst().NameLabelSet(nameLabel) self.Complete() - except Exception, e: + except Exception as e: self.Complete(Lang("Name Change Failed: ")+str(e)) elif pane.CurrentInput().HandleKey(inKey): @@ -415,7 +415,7 @@ def HandleRenewChoice(self): if ipAddress == '': ipAddress = Lang('') Layout.Inst().PushDialogue(InfoDialogue(Lang("DHCP Renewed with IP address ")+ipAddress)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Renewal Failed"), Lang(e))) def Commit(self): diff --git a/plugins-base/XSFeatureKeyboard.py b/plugins-base/XSFeatureKeyboard.py index 8b0676d..9a68f84 100644 --- a/plugins-base/XSFeatureKeyboard.py +++ b/plugins-base/XSFeatureKeyboard.py @@ -101,7 +101,7 @@ def HandleNameChoice(self, inChoice): else: try: self.Commit(inChoice) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Missing keymap: ")+Lang(e))) def HandleKeymapChoice(self, inChoice): @@ -116,7 +116,7 @@ def Commit(self, inKeymap): message = Lang('Keyboard type set to ')+data.KeymapToName(inKeymap) Layout.Inst().PushDialogue(InfoDialogue( message)) XSLog(message) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration failed: ")+Lang(e))) data.Update() diff --git a/plugins-base/XSFeatureNTP.py b/plugins-base/XSFeatureNTP.py index ad58811..b855411 100644 --- a/plugins-base/XSFeatureNTP.py +++ b/plugins-base/XSFeatureNTP.py @@ -111,7 +111,7 @@ def HandleKeyADD(self, inKey): servers.append(inputValues['name']) data.NTPServersSet(servers) self.Commit(Lang("NTP server")+" "+inputValues['name']+" "+Lang("added")) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang(e))) elif pane.CurrentInput().HandleKey(inKey): pass # Leave handled as True @@ -160,7 +160,7 @@ def HandleInitialChoice(self, inChoice): message = data.NTPStatus()+Lang("\n\n(Initial synchronization may take several minutes)") Layout.Inst().PushDialogue(InfoDialogue( Lang("NTP Status"), message)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Operation Failed"), Lang(e))) data.Update() @@ -183,7 +183,7 @@ def Commit(self, inMessage): Layout.Inst().TransientBanner(Lang("Restarting NTP daemon with new configuration...")) data.RestartService('chronyd') Layout.Inst().PushDialogue(InfoDialogue( inMessage)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Update failed: ")+Lang(e))) data.Update() diff --git a/plugins-base/XSFeaturePoolEject.py b/plugins-base/XSFeaturePoolEject.py index 573309b..692ca57 100644 --- a/plugins-base/XSFeaturePoolEject.py +++ b/plugins-base/XSFeaturePoolEject.py @@ -96,7 +96,7 @@ def Commit(self): hostUtils.DoOperation('eject', HotAccessor().local_host_ref()) Layout.Inst().ExitBannerSet(Lang('Removal Successful. This Host Will Now Reboot...')) Layout.Inst().ExitCommandSet('/bin/sleep 120') - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Failed to Remove Host from Pool"), Lang(e))) class XSFeaturePoolEject: diff --git a/plugins-base/XSFeaturePoolJoin.py b/plugins-base/XSFeaturePoolJoin.py index e1abbf2..7fa1ca9 100644 --- a/plugins-base/XSFeaturePoolJoin.py +++ b/plugins-base/XSFeaturePoolJoin.py @@ -102,7 +102,7 @@ def HandleKeyGATHER(self, inKey): try: IPUtils.AssertValidNetworkName(self.params['hostname']) self.ChangeState('CONFIRM') - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang(e))) @@ -149,7 +149,7 @@ def Commit(self): self.params['hostname'], self.params['username'], self.params['password']) Layout.Inst().PushDialogue(ProgressDialogue(task, Lang("Joining Pool with Master '")+self.params['hostname']+"'")) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Host Failed to Join the Pool"), Lang(e))) class XSFeaturePoolJoin: diff --git a/plugins-base/XSFeaturePoolNewMaster.py b/plugins-base/XSFeaturePoolNewMaster.py index 6685970..4d2ba3f 100644 --- a/plugins-base/XSFeaturePoolNewMaster.py +++ b/plugins-base/XSFeaturePoolNewMaster.py @@ -102,7 +102,7 @@ def Commit(self): Layout.Inst().TransientBanner(Lang('Designating New Pool Master...')) hostUtils.DoOperation('designate_new_master', self.newMaster.HotOpaqueRef()) Layout.Inst().PushDialogue(InfoDialogue(Lang("The Pool Master Has Been Changed"), Lang('Please allow several seconds for the change to propagate throughout the Pool.'))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Failed to Designate New Pool Master"), Lang(e))) class XSFeaturePoolNewMaster: diff --git a/plugins-base/XSFeatureReboot.py b/plugins-base/XSFeatureReboot.py index deaff3f..bedf0b9 100644 --- a/plugins-base/XSFeatureReboot.py +++ b/plugins-base/XSFeatureReboot.py @@ -38,13 +38,13 @@ def RebootReplyHandler(cls, inYesNo): Data.Inst().LocalHostDisable() except XenAPI.Failure: raise - except Exception, e: + except Exception as e: # Ignore non-xapi failure - we want HA to veto the reboot but not other problems XSLogFailure('Host disable before reboot failed', e) Layout.Inst().ExitBannerSet(Lang("Rebooting...")) Layout.Inst().ExitCommandSet('/sbin/shutdown -r now') XSLog('Initiating reboot') - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Reboot Failed"), Lang(e))) @classmethod diff --git a/plugins-base/XSFeatureRemoteShell.py b/plugins-base/XSFeatureRemoteShell.py index e666c0f..1bdf83a 100644 --- a/plugins-base/XSFeatureRemoteShell.py +++ b/plugins-base/XSFeatureRemoteShell.py @@ -70,7 +70,7 @@ def HandleChoice(self, inChoice): Layout.Inst().PushDialogue(InfoDialogue(message)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Failed: ")+Lang(e))) data.Update() diff --git a/plugins-base/XSFeatureSRCommon.py b/plugins-base/XSFeatureSRCommon.py index 5782da6..d894b06 100644 --- a/plugins-base/XSFeatureSRCommon.py +++ b/plugins-base/XSFeatureSRCommon.py @@ -33,7 +33,7 @@ class SRUtils: def AllowedOperations(cls): if Auth.Inst().IsTestMode(): # Allow a lot more in test mode - retVal = cls.operationNames.keys() + retVal = list(cls.operationNames.keys()) else: retVal = ['forget', 'xsconsole-detach','xsconsole-destroy'] return retVal @@ -49,7 +49,7 @@ def AsyncOperation(cls, inOperation, inSRHandle, inParam0 = None): for pbd in sr.PBDs: try: Task.Sync(lambda x: x.xenapi.PBD.destroy(pbd.HotOpaqueRef().OpaqueRef())) - except Exception, e: + except Exception as e: storedError = e if storedError is not None: @@ -69,7 +69,7 @@ def AsyncOperation(cls, inOperation, inSRHandle, inParam0 = None): for pbd in sr.PBDs: try: Task.Sync(lambda x: x.xenapi.PBD.plug(pbd.HotOpaqueRef().OpaqueRef())) - except Exception, e: + except Exception as e: storedError = e if storedError is not None: @@ -88,7 +88,7 @@ def AsyncOperation(cls, inOperation, inSRHandle, inParam0 = None): for pbd in unplugged: try: Task.Sync(lambda x: x.xenapi.PBD.plug(pbd.HotOpaqueRef().OpaqueRef())) - except Exception, e: + except Exception as e: XSLogFailure('SR undo failed', e) raise # Reraise the original exception @@ -187,7 +187,7 @@ def __init__(self, inSRHandle): choiceList = [ name for name in allowedOps if name in SRUtils.AllowedOperations() ] - choiceList.sort(lambda x, y: cmp(SRUtils.OperationPriority(x), SRUtils.OperationPriority(y))) + choiceList.sort(key=lambda choice: SRUtils.OperationPriority(choice)) self.controlMenu = Menu() for choice in choiceList: @@ -289,7 +289,7 @@ def Commit(self): task = SRUtils.DoOperation(self.operation, self.srHandle, *self.opParams) Layout.Inst().PushDialogue(InfoDialogue(messagePrefix + Lang("successful"), )) - except Exception, e: + except Exception as e: self.ChangeState('INITIAL') Layout.Inst().PushDialogue(InfoDialogue(messagePrefix + Lang("failed"), Lang(e))) diff --git a/plugins-base/XSFeatureSRCreate.py b/plugins-base/XSFeatureSRCreate.py index 1ef7383..9b2aec9 100644 --- a/plugins-base/XSFeatureSRCreate.py +++ b/plugins-base/XSFeatureSRCreate.py @@ -545,7 +545,7 @@ def HandleKeyGATHER_NFS(self, inKey): Layout.Inst().TransientBanner(Lang('Probing for Storage Repositories...')) self.HandleCommonData(inputValues) self.HandleNFSData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -563,7 +563,7 @@ def HandleKeyGATHER_CIFS_ISO(self, inKey): inputValues = pane.GetFieldValues() self.HandleCommonData(inputValues) self.HandleCIFSData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -578,7 +578,7 @@ def HandleKeyGATHER_ISCSI(self, inKey): inputValues = pane.GetFieldValues() self.HandleCommonData(inputValues) self.HandleISCSIData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -594,7 +594,7 @@ def HandleKeyGATHER_NETAPP(self, inKey): Layout.Inst().TransientBanner(Lang('Probing NetApp...')) self.HandleCommonData(inputValues) self.HandleNetAppData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -609,7 +609,7 @@ def HandleKeyGATHER_HBA(self, inKey): # No input fields for HBA Layout.Inst().TransientBanner(Lang('Probing for HBA Devices...')) self.HandleHBAData({}) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: handled = False @@ -631,7 +631,7 @@ def HandleKeyPROBE_HBA_NAME(self, inKey): self.ChangeState('PROBE_HBA_SR') else: self.ChangeState('CONFIRM') - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -647,7 +647,7 @@ def HandleKeyGATHER_EQUAL(self, inKey): Layout.Inst().TransientBanner(Lang('Probing Dell EqualLogic Server...')) self.HandleCommonData(inputValues) self.HandleEqualData(inputValues) - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) else: @@ -667,7 +667,7 @@ def HandleKeyPROBE_ISCSI_IQN(self, inKey): message += Lang("IQN", 12)+iqn.name Layout.Inst().PushDialogue(InfoDialogue( Lang("IQN Information"), message)) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Failed: ")+Lang(e))) handled = True else: @@ -693,7 +693,7 @@ def HandleKeyPROBE_NETAPP_FLEXVOLS(self, inKey): raise Exception(Lang('The number of FlexVols must be between 1 and 32')) self.srParams['numflexvols'] = numFlexVols self.ChangeState('PROBE_NETAPP_PROVISIONING') - except Exception, e: + except Exception as e: pane.InputIndexSet(None) Layout.Inst().PushDialogue(InfoDialogue(Lang("Invalid Value"), Lang(e))) else: @@ -724,7 +724,7 @@ def HandleKeyCONFIRM(self, inKey): try: # Despatch method named 'Commit'+self.srCreateType+'_'+self.variant getattr(self, 'Commit'+self.createType+'_'+self.variant)() - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue(Lang("Operation Failed"), Lang(e))) handled = True @@ -816,7 +816,7 @@ def HandleISCSIData(self, inParams): self.srTypes['ISCSI'] # type ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'SR_BACKEND_FAILURE_96': raise # Parse XML for UUID values @@ -833,7 +833,7 @@ def HandleISCSIData(self, inParams): name=iqn, iqn=iqn)) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_ISCSI_IQN') @@ -876,7 +876,7 @@ def HandleNetAppData(self, inParams): True # shared ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'SR_BACKEND_FAILURE_123': raise # Parse XML for UUID values @@ -897,7 +897,7 @@ def HandleNetAppData(self, inParams): raidType = raidType, asisdedup = asisdedup)) # NetApp's Advanced Single Instance Storage Deduplication, 'true' if supported - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_NETAPP_AGGREGATE') elif self.variant=='ATTACH': @@ -922,7 +922,7 @@ def HandleNetAppData(self, inParams): aggregate = aggregate )) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_NETAPP_SR') @@ -940,7 +940,7 @@ def HandleHBAData(self, inParams): self.srTypes['HBA'], # type ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'SR_BACKEND_FAILURE_107': raise # Parse XML for UUID values @@ -954,7 +954,7 @@ def HandleHBAData(self, inParams): setattr(deviceInfo, name.lower(), str(device.getElementsByTagName(name)[0].firstChild.nodeValue.strip())) self.deviceChoices.append(deviceInfo) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_HBA_DEVICE') @@ -996,7 +996,7 @@ def HandleEqualData(self, inParams): True # shared ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'SR_BACKEND_FAILURE_163': raise # Parse XML for UUID values @@ -1010,7 +1010,7 @@ def HandleEqualData(self, inParams): setattr(storageInfo, name.lower(), storagePool.getElementsByTagName(name)[0].firstChild.nodeValue.strip()) self.storagePoolChoices.append(storageInfo) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_EQUAL_STORAGEPOOL') elif self.variant=='ATTACH': @@ -1033,7 +1033,7 @@ def HandleEqualData(self, inParams): size = size )) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_EQUAL_SR') @@ -1068,7 +1068,7 @@ def HandleIQNChoice(self, inChoice): self.srTypes['ISCSI'] # type ) ) - except XenAPI.Failure, e: + except XenAPI.Failure as e: # Parse XML for UUID values if e.details[0] != 'SR_BACKEND_FAILURE_107': raise @@ -1082,7 +1082,7 @@ def HandleIQNChoice(self, inChoice): self.lunChoices.append(record) - except Exception, e: + except Exception as e: pass # Ignore failures self.ChangeState('PROBE_ISCSI_LUN') @@ -1187,7 +1187,7 @@ def CommitCreate(self, inType, inDeviceConfig, inOtherConfig = None): ) # Set values in other_config only if the SR.create operation hasn't already set them - for key, value in FirstValue(inOtherConfig, {}).iteritems(): + for key, value in FirstValue(inOtherConfig, {}).items(): try: Task.Sync(lambda x:x.xenapi.SR.add_to_other_config(srRef, key, value)) except: @@ -1197,7 +1197,7 @@ def CommitCreate(self, inType, inDeviceConfig, inOtherConfig = None): Data.Inst().SetPoolSRIfRequired(srRef) Layout.Inst().PushDialogue(InfoDialogue(Lang("Storage Repository Creation Successful"))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Storage Repository Creation Failed"), Lang(e))) def CommitAttach(self, inType, inDeviceConfig, inOtherConfig, inContentType): @@ -1230,7 +1230,7 @@ def CommitAttach(self, inType, inDeviceConfig, inOtherConfig, inContentType): ) # Set values in other_config only if the SR.introduce operation hasn't already set them - for key, value in FirstValue(inOtherConfig, {}).iteritems(): + for key, value in FirstValue(inOtherConfig, {}).items(): try: Task.Sync(lambda x:x.xenapi.SR.add_to_other_config(srRef, key, value)) except: @@ -1252,7 +1252,7 @@ def CommitAttach(self, inType, inDeviceConfig, inOtherConfig, inContentType): Data.Inst().SetPoolSRIfRequired(srRef) Layout.Inst().PushDialogue(InfoDialogue(Lang("Storage Repository Attachment Successful"))) - except Exception, e: + except Exception as e: message = Lang(e) # Attempt to undo the work we've done, because the SR is incomplete try: @@ -1263,7 +1263,7 @@ def CommitAttach(self, inType, inDeviceConfig, inOtherConfig, inContentType): Task.Sync(lambda x: x.xenapi.SR.forget(srRef)) - except Exception, e: + except Exception as e: message += Lang('. Attempts to rollback also failed: ')+Lang(e) Layout.Inst().PushDialogue(InfoDialogue(Lang("Storage Repository Attachment Failed"), message)) diff --git a/plugins-base/XSFeatureSRInfo.py b/plugins-base/XSFeatureSRInfo.py index 8ee9825..55cefc0 100644 --- a/plugins-base/XSFeatureSRInfo.py +++ b/plugins-base/XSFeatureSRInfo.py @@ -112,7 +112,7 @@ def MenuRegenerator(cls, inList, inMenu): srList = [ sr for sr in HotAccessor().visible_sr if sr.other_config({}).get('xensource_internal', '') != 'true' ] # Sort list by SR shared flag then name - srList.sort(lambda x, y: cmp(y.shared(False), x.shared(False)) or cmp (x.name_label(''), y.name_label())) + srList.sort(key=lambda sr: (-sr.shared(False), sr.name_label(''))) srUtils = Importer.GetResource('SRUtils') for sr in srList: diff --git a/plugins-base/XSFeatureSaveBugReport.py b/plugins-base/XSFeatureSaveBugReport.py index e68d194..ef2f4b7 100644 --- a/plugins-base/XSFeatureSaveBugReport.py +++ b/plugins-base/XSFeatureSaveBugReport.py @@ -60,14 +60,14 @@ def DoAction(self): Layout.Inst().PushDialogue(InfoDialogue( Lang("Saved Bug Report"))) - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue( Lang("Save Failed"), Lang(e))) finally: try: self.PreExitActions() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Save Failed"), Lang(e))) class XSFeatureSaveBugReport: diff --git a/plugins-base/XSFeatureShutdown.py b/plugins-base/XSFeatureShutdown.py index bc1185a..3370fe8 100644 --- a/plugins-base/XSFeatureShutdown.py +++ b/plugins-base/XSFeatureShutdown.py @@ -38,13 +38,13 @@ def ShutdownReplyHandler(cls, inYesNo): Data.Inst().LocalHostDisable() except XenAPI.Failure: raise - except Exception, e: + except Exception as e: # Ignore non-xapi failure - we want HA to veto the shutdown but not other problems XSLogFailure('Host disable before shutdown failed', e) Layout.Inst().ExitBannerSet(Lang("Shutting Down...")) Layout.Inst().ExitCommandSet('/sbin/shutdown -h now') XSLog('Initiated shutdown') - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Shutdown Failed"), Lang(e))) @classmethod diff --git a/plugins-base/XSFeatureSuspendSR.py b/plugins-base/XSFeatureSuspendSR.py index 99c6d95..b9955d4 100644 --- a/plugins-base/XSFeatureSuspendSR.py +++ b/plugins-base/XSFeatureSuspendSR.py @@ -37,7 +37,7 @@ def DoAction(self, inSR): Data.Inst().SuspendSRSet(inSR) Layout.Inst().PushDialogue(InfoDialogue( Lang('Configuration Successful'), Lang("Suspend SR set to '"+inSR['name_label']+"'"))) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration failed: ")+str(e))) Data.Inst().Update() diff --git a/plugins-base/XSFeatureSystem.py b/plugins-base/XSFeatureSystem.py index 6608c2e..7c55722 100644 --- a/plugins-base/XSFeatureSystem.py +++ b/plugins-base/XSFeatureSystem.py @@ -69,7 +69,7 @@ def StatusUpdateHandlerPROCESSOR(cls, inPane): inPane.NewLine() inPane.AddTitleField(Lang("Description")) - for name, value in data.derived.cpu_name_summary().iteritems(): + for name, value in data.derived.cpu_name_summary().items(): # Use DMI number for populated sockets, not xapi-reported number of logical cores inPane.AddWrappedTextField(str(data.dmi.cpu_populated_sockets())+" x "+name) diff --git a/plugins-base/XSFeatureTestNetwork.py b/plugins-base/XSFeatureTestNetwork.py index 5d25e15..e56c5d8 100644 --- a/plugins-base/XSFeatureTestNetwork.py +++ b/plugins-base/XSFeatureTestNetwork.py @@ -126,7 +126,7 @@ def DoPing(self, inAddress): try: Layout.Inst().TransientBanner(Lang('Pinging...')) (success, output) = Data.Inst().Ping(inAddress) - except Exception, e: + except Exception as e: output = Lang(e) if success: diff --git a/plugins-base/XSFeatureTimezone.py b/plugins-base/XSFeatureTimezone.py index b5e0522..529a7bb 100644 --- a/plugins-base/XSFeatureTimezone.py +++ b/plugins-base/XSFeatureTimezone.py @@ -41,7 +41,7 @@ def BuildPane(self): self.cityList = [] choiceDefs = [] cityExp = re.compile(self.continentChoice) - keys = Data.Inst().timezones.cities({}).keys() + keys = list(Data.Inst().timezones.cities({}).keys()) keys.sort() for city in keys: if cityExp.match(city): @@ -112,7 +112,7 @@ def HandleCityChoice(self, inChoice): message = Lang('The timezone has been set to ')+city +".\n\nLocal time is now "+data.CurrentTimeString() Layout.Inst().PushDialogue(InfoDialogue( Lang('Timezone Set'), message)) XSLog(message) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration failed: ")+Lang(e))) data.Update() diff --git a/plugins-base/XSFeatureVMCommon.py b/plugins-base/XSFeatureVMCommon.py index 39fe497..e25bf87 100644 --- a/plugins-base/XSFeatureVMCommon.py +++ b/plugins-base/XSFeatureVMCommon.py @@ -34,7 +34,7 @@ class VMUtils: } @classmethod def AllowedOperations(cls): - return cls.operationNames.keys() + return list(cls.operationNames.keys()) @classmethod def AsyncOperation(cls, inOperation, inVMHandle, inParam0 = None): @@ -127,7 +127,7 @@ def __init__(self, inVMHandle): choiceList = [ name for name in allowedOps if name in VMUtils.AllowedOperations() ] - choiceList.sort(lambda x, y: cmp(VMUtils.OperationPriority(x), VMUtils.OperationPriority(y))) + choiceList.sort(key=lambda choice: VMUtils.OperationPriority(choice)) self.controlMenu = Menu() for choice in choiceList: @@ -146,7 +146,7 @@ def BuildPane(self): if self.state == 'MIGRATE': hosts = VMUtils.GetPossibleHostAccessors(self.vmHandle) - hosts.sort(lambda x, y: cmp(x.name_label(), y.name_label())) + hosts.sort(key=lambda host: host.name_label()) self.hostMenu = Menu() residentHost = HotAccessor().vm[self.vmHandle].resident_on() for host in hosts: @@ -251,7 +251,7 @@ def Commit(self): task = VMUtils.AsyncOperation(self.operation, self.vmHandle, *self.opParams) Layout.Inst().PushDialogue(ProgressDialogue(task, messagePrefix)) - except Exception, e: + except Exception as e: self.ChangeState('INITIAL') Layout.Inst().PushDialogue(InfoDialogue(messagePrefix + Lang("Failed"), Lang(e))) diff --git a/plugins-base/XSFeatureVMInfo.py b/plugins-base/XSFeatureVMInfo.py index 8305d69..903c26d 100644 --- a/plugins-base/XSFeatureVMInfo.py +++ b/plugins-base/XSFeatureVMInfo.py @@ -47,7 +47,7 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): else: try: vmMetrics = HotMetrics.Inst().VMMetrics(vm.uuid()) - except Exception, e: + except Exception as e: XSLogFailure('VMMetrics failed', e) vmMetrics = {} @@ -66,7 +66,7 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): else: cpuUsageStr = Lang('') - except Exception, e: + except Exception as e: cpuUsageStr = Lang('') inPane.AddStatusField(Lang("CPU Usage", 16), cpuUsageStr) @@ -80,7 +80,7 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): memoryUsage = usedMemory / totalMemory memoryUsage = max(0, min(memoryUsage, 1)) memoryUsageStr = "%d%% (%s)" % (int(memoryUsage * 100), SizeUtils.MemorySizeString(usedMemory)) - except Exception, e: + except Exception as e: memoryUsageStr = Lang('') inPane.AddStatusField(Lang("Memory Usage", 16), memoryUsageStr) @@ -89,7 +89,7 @@ def InfoStatusUpdateHandler(cls, inPane, inHandle): networks = vm.guest_metrics.networks({}) for key in sorted(networks.keys()): inPane.AddStatusField((Lang('Network ')+key).ljust(16, ' '), networks[key]) - except Exception, e: + except Exception as e: inPane.AddStatusField(Lang('Network Info', 16), Lang('')) inPane.AddKeyHelpField( { Lang("") : Lang("Control This Virtual Machine") } ) @@ -118,7 +118,7 @@ def MenuRegenerator(cls, inList, inMenu): # inList is a list of HotOpaqueRef objects vmList = [ HotAccessor().vm[x] for x in inList ] # Sort list by VM name - vmList.sort(lambda x,y: cmp(x.name_label(''), y.name_label(''))) + vmList.sort(key=lambda vm: vm.name_label('')) for vm in vmList: nameLabel = vm.name_label(Lang('')) @@ -141,7 +141,7 @@ def ResidentMenuRegenerator(cls, inName, inMenu): @classmethod def AllMenuRegenerator(cls, inName, inMenu): # Fetching all guest_vm is an expensive operation (implies xenapi.vm.get_all_records) - return cls.MenuRegenerator(HotAccessor().guest_vm({}).keys(), inMenu) + return cls.MenuRegenerator(list(HotAccessor().guest_vm({}).keys()), inMenu) def Register(self): Importer.RegisterMenuEntry( diff --git a/plugins-base/XSFeatureXAPIConnection.py b/plugins-base/XSFeatureXAPIConnection.py index cf566a1..e0ffebd 100644 --- a/plugins-base/XSFeatureXAPIConnection.py +++ b/plugins-base/XSFeatureXAPIConnection.py @@ -27,7 +27,7 @@ def HandleRestartChoice(inChoice): Layout.Inst().TransientBanner(Lang("Restarting xapi....")) Data.Inst().StartXAPI() XSLog('Restarted xapi') - except Exception, e: + except Exception as e: XSLogFailure('Failed to restart xapi', e) Layout.Inst().PushDialogue(InfoDialogue(Lang('Restart Failed'), Lang('Xapi did not restart successfully. More information may be available in the file /var/log/xensource.log.'))) diff --git a/plugins-oem/XSFeatureClaimSR.py b/plugins-oem/XSFeatureClaimSR.py index b928e2b..0b63aff 100644 --- a/plugins-oem/XSFeatureClaimSR.py +++ b/plugins-oem/XSFeatureClaimSR.py @@ -325,7 +325,7 @@ def DoAction(self): try: Data.Inst().SetPoolSRsFromDeviceIfNotSet(self.deviceToErase.device) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang("Disk claimed, but could not set as default SR: ") + Lang(e))) # Continue to reboot dialogue diff --git a/plugins-oem/XSFeatureOEMBackup.py b/plugins-oem/XSFeatureOEMBackup.py index 9049986..9c01c57 100644 --- a/plugins-oem/XSFeatureOEMBackup.py +++ b/plugins-oem/XSFeatureOEMBackup.py @@ -78,7 +78,7 @@ def DoCommit(self): Lang("Backup Successful"))) XSLog('Backup successful') - except Exception, e: + except Exception as e: try: os.unlink(filename) except: pass Layout.Inst().PopDialogue() @@ -87,7 +87,7 @@ def DoCommit(self): finally: try: self.PreExitActions() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Backup Failed"), Lang(e))) diff --git a/plugins-oem/XSFeatureOEMRestore.py b/plugins-oem/XSFeatureOEMRestore.py index 9207b02..67b8014 100644 --- a/plugins-oem/XSFeatureOEMRestore.py +++ b/plugins-oem/XSFeatureOEMRestore.py @@ -69,7 +69,7 @@ def DoAction(self): XSLog('Restore successful') hostEnabled = False - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue( Lang("Restore Failed"), Lang(e))) @@ -79,7 +79,7 @@ def DoAction(self): if hostEnabled: # Dont leave the host disabled if restoration has failed Data.Inst().LocalHostEnable() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Restore Failed"), Lang(e))) diff --git a/plugins-oem/XSFeatureReset.py b/plugins-oem/XSFeatureReset.py index 1eb190b..3bfff19 100644 --- a/plugins-oem/XSFeatureReset.py +++ b/plugins-oem/XSFeatureReset.py @@ -102,7 +102,7 @@ def DoAction(self): try: Layout.Inst().TransientBanner(Lang('Stopping Virtual Machines...')) ShellPipe('service', 'xapi-domains', 'stop').Call() - except Exception, e: + except Exception as e: Layout.Inst().TransientBanner(Lang('Could not stop Virtual Machines: ' + Lang(e))) time.sleep(3.0) try: @@ -111,7 +111,7 @@ def DoAction(self): Layout.Inst().TransientBanner(Lang('Rebooting...')) Layout.Inst().ExitBannerSet(Lang("Rebooting...")) Layout.Inst().SubshellCommandSet("/sbin/reboot -f") # -f avoids running init scripts on shutdown - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue(Lang('Reset to Factory Defaults Failed'), Lang(e))) class XSFeatureReset: diff --git a/plugins-oem/XSFeatureUpdate.py b/plugins-oem/XSFeatureUpdate.py index 88bc7fb..a761f5c 100644 --- a/plugins-oem/XSFeatureUpdate.py +++ b/plugins-oem/XSFeatureUpdate.py @@ -69,7 +69,7 @@ def DoAction(self): XSLog('Software updated') hostEnabled = False - except Exception, e: + except Exception as e: Layout.Inst().PopDialogue() Layout.Inst().PushDialogue(InfoDialogue( Lang("Software Update Failed"), Lang(e))) @@ -79,7 +79,7 @@ def DoAction(self): if hostEnabled: # Dont leave the host disabled if the update has failed Data.Inst().LocalHostEnable() - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Software Update Failed"), Lang(e))) class XSFeatureUpdate: diff --git a/plugins-oem/XSFeatureVerboseBoot.py b/plugins-oem/XSFeatureVerboseBoot.py index b13114f..0e8ad31 100644 --- a/plugins-oem/XSFeatureVerboseBoot.py +++ b/plugins-oem/XSFeatureVerboseBoot.py @@ -56,7 +56,7 @@ def HandleChoice(self, inChoice): try: data.SetVerboseBoot(inChoice) - except Exception, e: + except Exception as e: Layout.Inst().PushDialogue(InfoDialogue( Lang("Failed: ")+Lang(e))) else: Layout.Inst().PushDialogue(InfoDialogue( Lang("Configuration Updated"))) diff --git a/simpleconfig.py b/simpleconfig.py index 4bd665a..a7a68ce 100644 --- a/simpleconfig.py +++ b/simpleconfig.py @@ -18,30 +18,32 @@ import os import shutil + # use our own ASCII only uppercase function to avoid locale issues # not going to be fast but not important def uppercase_ASCII_string(str): newstr = "" - for i in range(0,len(str)): - if str[i] in string.lowercase: - newstr += chr(ord(str[i])-32) - else: - newstr += str[i] + for i in range(0, len(str)): + if str[i].islower(): + newstr += chr(ord(str[i]) - 32) + else: + newstr += str[i] return newstr + class SimpleConfigFile: - def __str__ (self): + def __str__(self): s = "" - keys = self.info.keys () - keys.sort () + keys = list(self.info.keys()) + keys.sort() for key in keys: # FIXME - use proper escaping - if type (self.info[key]) == type(""): + if type(self.info[key]) == type(""): s = s + key + "=\"" + self.info[key] + "\"\n" return s - def __init__ (self): + def __init__(self): self.info = {} def write(self, file): @@ -69,17 +71,17 @@ def read(self, file): value = value.replace("'", '') self.info[key] = value - def set (self, *args): + def set(self, *args): for (key, data) in args: self.info[uppercase_ASCII_string(key)] = data - def unset (self, *keys): + def unset(self, *keys): for key in keys: key = uppercase_ASCII_string(key) - if self.info.has_key (key): - del self.info[key] + if key in self.info: + del self.info[key] - def get (self, key): + def get(self, key): key = uppercase_ASCII_string(key) return self.info.get(key, "") @@ -132,4 +134,3 @@ def write(self, dir=None): path = os.path.join(dir, os.path.basename(self.path)) SimpleConfigFile.write(self, path) -