diff --git a/MaintenanceReadme.txt b/MaintenanceReadme.txt index a370de3..f8eac57 100644 --- a/MaintenanceReadme.txt +++ b/MaintenanceReadme.txt @@ -23,10 +23,10 @@ Guidelines for using HotAccessor are: (v) Iteration over accessors is generally better than iteration over results, e.g. These print the same thing: for sr in HotAccessor().sr: # Iterate over HotAccessors - print sr.name_label() + print(sr.name_label()) for value in HotAccessor().sr().values(): # Iterate over the returned dict of all SRs - print value['name_label'] + print(value['name_label']) (vi) List comprehensions also work diff --git a/XSConsole.py b/XSConsole.py index f6a8883..15931c1 100755 --- a/XSConsole.py +++ b/XSConsole.py @@ -15,6 +15,7 @@ # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. +from __future__ import print_function import sys, traceback from XSConsoleConfig import * @@ -27,9 +28,9 @@ 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'] ) diff --git a/XSConsoleBases.py b/XSConsoleBases.py index abf69de..214ad3c 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): diff --git a/XSConsoleCurses.py b/XSConsoleCurses.py index f2fbb2b..185c3ed 100644 --- a/XSConsoleCurses.py +++ b/XSConsoleCurses.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 curses, sys, commands +import curses, sys from XSConsoleBases import * from XSConsoleConfig import * diff --git a/XSConsoleData.py b/XSConsoleData.py index 85261fd..4c36ac5 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 @@ -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: @@ -301,7 +301,7 @@ 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: @@ -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', []): @@ -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): @@ -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'] = { @@ -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 @@ -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: @@ -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 5947720..18b48ad 100644 --- a/XSConsoleDataUtils.py +++ b/XSConsoleDataUtils.py @@ -80,7 +80,7 @@ def DeviceList(cls, inWritableOnly): @classmethod def SRDeviceList(self): retVal= [] - status, output = commands.getstatusoutput("/opt/xensource/libexec/list_local_disks") + status, output = subprocess.getstatusoutput("/opt/xensource/libexec/list_local_disks") if status == 0: regExp = re.compile(r"\s*\(\s*'([^']*)'\s*,\s*'([^']*)'\s*,\s*'([^']*)'\s*,\s*'([^']*)'\s*,\s*'([^']*)'\s*\)") for line in output.split("\n"): @@ -168,18 +168,18 @@ def USBFormat(self, inVDI): if e.errno != errno.EINTR: # Loop if EINTR raise - status, output = commands.getstatusoutput('/bin/sync') + status, output = subprocess.getstatusoutput('/bin/sync') if status != 0: raise Exception(output) # Format the new partition with VFAT - status, output = commands.getstatusoutput("/sbin/mkfs.vfat -n 'XenServer Backup' -F 32 '" +partitionName + "' 2>&1") + status, output = subprocess.getstatusoutput("/sbin/mkfs.vfat -n 'XenServer Backup' -F 32 '" +partitionName + "' 2>&1") if status != 0: raise Exception(output) - status, output = commands.getstatusoutput('/bin/sync') + status, output = subprocess.getstatusoutput('/bin/sync') if status != 0: raise Exception(output) @@ -237,7 +237,7 @@ def __init__(self, inVDI, inMode = None): FileUtils.AssertSafePath(self.mountDev) self.mountPoint = tempfile.mkdtemp(".xsconsole") - status, output = commands.getstatusoutput("/bin/mount -t auto -o " + self.mode + ' ' +self.mountDev+" "+self.mountPoint + " 2>&1") + status, output = subprocess.getstatusoutput("/bin/mount -t auto -o " + self.mode + ' ' +self.mountDev+" "+self.mountPoint + " 2>&1") if status != 0: try: self.Unmount() @@ -276,7 +276,7 @@ def HandleMountFailure(self, inOutput): raise Exception(inOutput) realDevice = FileUtils.DeviceFromVDI(self.vdi) - status, output = commands.getstatusoutput("/sbin/fdisk -l '" +realDevice+"'") + status, output = subprocess.getstatusoutput("/sbin/fdisk -l '" +realDevice+"'") if status != 0: raise Exception(output) @@ -313,7 +313,7 @@ def Scan(self, inRegExp = None, inNumToReturn = None): def Unmount(self): status = 0 if self.mountedVBD: - status, output = commands.getstatusoutput("/bin/umount '"+self.mountPoint + "' 2>&1") + status, output = subprocess.getstatusoutput("/bin/umount '"+self.mountPoint + "' 2>&1") os.rmdir(self.mountPoint) self.mountedVBD = False if self.pluggedVBD: @@ -360,7 +360,7 @@ def __init__(self, inVDI, inMode = None): FileUtils.AssertSafePath(self.mountDev) self.mountPoint = tempfile.mkdtemp(".xsconsole") - status, output = commands.getstatusoutput("/bin/mount -t auto -o " + self.mode + ' ' +self.mountDev+" "+self.mountPoint + " 2>&1") + status, output = subprocess.getstatusoutput("/bin/mount -t auto -o " + self.mode + ' ' +self.mountDev+" "+self.mountPoint + " 2>&1") if status != 0: try: self.Unmount() @@ -400,7 +400,7 @@ def HandleMountFailure(self, inStatus, inOutput): raise Exception(inOutput) realDevice = FileUtils.DeviceFromVDI(self.vdi) - status, output = commands.getstatusoutput("/sbin/fdisk -l '" +realDevice+"'") + status, output = subprocess.getstatusoutput("/sbin/fdisk -l '" +realDevice+"'") if status != 0: raise Exception(output) @@ -437,7 +437,7 @@ def Scan(self, inRegExp = None, inNumToReturn = None): def Unmount(self): status = 0 if self.mountedVDI: - status, output = commands.getstatusoutput("/bin/umount '"+self.mountPoint + "' 2>&1") + status, output = subprocess.getstatusoutput("/bin/umount '"+self.mountPoint + "' 2>&1") os.rmdir(self.mountPoint) self.mountedVDI = False XSLog('Unmounted '+self.mountPoint) diff --git a/XSConsoleFields.py b/XSConsoleFields.py index 6ed2b4f..adcd431 100644 --- a/XSConsoleFields.py +++ b/XSConsoleFields.py @@ -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 e05103e..3ae8a81 100644 --- a/XSConsoleHotData.py +++ b/XSConsoleHotData.py @@ -15,7 +15,7 @@ import XenAPI -import commands, re, shutil, sys, socket +import 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): + if isinstance(iterData, dict): self.iterKeys = iterData.keys() - elif isinstance(iterData, (types.ListType, types.TupleType)): + 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,8 +189,8 @@ 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)+"'") @@ -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,29 +449,29 @@ 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): + elif isinstance(value, list): for item in value: if isinstance(item, str) and item.startswith('OpaqueRef'): print('Missed OpaqueRef List in HotData item: '+key) break - elif isinstance(value, types.DictType): + elif isinstance(value, dict): for item in value.keys(): if isinstance(item, str) and item.startswith('OpaqueRef'): print('Missed OpaqueRef Dict in HotData item: '+key) @@ -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 454be61..c0f15e7 100644 --- a/XSConsoleImporter.py +++ b/XSConsoleImporter.py @@ -147,7 +147,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) @@ -178,10 +178,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/XSConsoleMenus.py b/XSConsoleMenus.py index e06937a..af64286 100644 --- a/XSConsoleMenus.py +++ b/XSConsoleMenus.py @@ -187,7 +187,7 @@ def Reset(self): 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 0e96199..4fb430e 100644 --- a/XSConsoleMetrics.py +++ b/XSConsoleMetrics.py @@ -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 @@ -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 diff --git a/XSConsoleState.py b/XSConsoleState.py index f0f786e..f38db45 100644 --- a/XSConsoleState.py +++ b/XSConsoleState.py @@ -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) 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 904f450..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() diff --git a/XSConsoleUtils.py b/XSConsoleUtils.py index 3ff451e..d2ad2b0 100644 --- a/XSConsoleUtils.py +++ b/XSConsoleUtils.py @@ -51,7 +51,7 @@ def __init__(self, *inParams): 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 @@ -84,7 +84,7 @@ def Communicate(self, inInput = None): 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) diff --git a/plugins-base/XSFeatureDRBackup.py b/plugins-base/XSFeatureDRBackup.py index c4ab9c7..e9350c6 100644 --- a/plugins-base/XSFeatureDRBackup.py +++ b/plugins-base/XSFeatureDRBackup.py @@ -16,6 +16,8 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") +import subprocess + from XSConsoleStandard import * class DRBackupDialogue(SRDialogue): @@ -36,7 +38,7 @@ def DoAction(self, inSR): sr_uuid = inSR['uuid'] command = "%s/xe-backup-metadata -n -u %s" % (Config.Inst().HelperPath(), sr_uuid) - status, output = commands.getstatusoutput(command) + status, output = subprocess.getstatusoutput(command) status = os.WEXITSTATUS(status) initalize_vdi = "" if status == 3: @@ -46,7 +48,7 @@ def DoAction(self, inSR): Layout.Inst().TransientBanner(Lang("Backing up metadata... This may take several minutes.")) command = "%s/xe-backup-metadata %s -u %s" % (Config.Inst().HelperPath(), initalize_vdi, sr_uuid) - status, output = commands.getstatusoutput(command) + status, output = subprocess.getstatusoutput(command) if status == 0: Layout.Inst().PushDialogue(InfoDialogue(Lang("Backup Successful"), output)) else: diff --git a/plugins-base/XSFeatureDRRestore.py b/plugins-base/XSFeatureDRRestore.py index 197a3ce..a8aedb6 100644 --- a/plugins-base/XSFeatureDRRestore.py +++ b/plugins-base/XSFeatureDRRestore.py @@ -92,7 +92,7 @@ def HandleMethodChoice(self, inChoice, dryRun): dry_flag="" Layout.Inst().TransientBanner(Lang("Restoring VM Metadata. This may take a few minutes...")) command = "%s/xe-restore-metadata -y %s -u %s -x %s -d %s -m %s" % (Config.Inst().HelperPath(), dry_flag, self.sr_uuid, self.vdi_uuid, self.chosen_date, chosen_mode) - status, output = commands.getstatusoutput(command) + status, output = subprocess.getstatusoutput(command) status = os.WEXITSTATUS(status) Layout.Inst().PopDialogue() if status == 0: diff --git a/plugins-base/XSFeatureSRCreate.py b/plugins-base/XSFeatureSRCreate.py index 5326763..c29d258 100644 --- a/plugins-base/XSFeatureSRCreate.py +++ b/plugins-base/XSFeatureSRCreate.py @@ -16,6 +16,8 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") +import subprocess + from XSConsoleStandard import * import xml.dom.minidom @@ -1187,7 +1189,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: @@ -1230,7 +1232,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: @@ -1286,7 +1288,7 @@ def CommitNFS_ATTACH(self): 'user') def CommitNFS_ISO_ATTACH(self): - self.srParams['uuid'] = commands.getoutput('/usr/bin/uuidgen') + self.srParams['uuid'] = subprocess.getoutput('/usr/bin/uuidgen') self.CommitAttach(self.srTypes['NFS_ISO'], { # device_config 'location':self.srParams['server']+':'+self.srParams['serverpath'], 'options':self.srParams['options'] @@ -1298,7 +1300,7 @@ def CommitNFS_ISO_ATTACH(self): ) def CommitCIFS_ISO_ATTACH(self): - self.srParams['uuid'] = commands.getoutput('/usr/bin/uuidgen') + self.srParams['uuid'] = subprocess.getoutput('/usr/bin/uuidgen') deviceConfig = { 'location':'//'+self.srParams['server']+'/'+self.srParams['serverpath'], 'type':'cifs', diff --git a/plugins-base/XSFeatureSaveBugReport.py b/plugins-base/XSFeatureSaveBugReport.py index ef2f4b7..cc9e3dc 100644 --- a/plugins-base/XSFeatureSaveBugReport.py +++ b/plugins-base/XSFeatureSaveBugReport.py @@ -16,6 +16,8 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") +import subprocess + from XSConsoleStandard import * class SaveBugReportDialogue(FileDialogue): @@ -50,7 +52,7 @@ def DoAction(self): file = open(filename, "w") # xen-bugtool requires a value for $USER command = "( export USER=root && /usr/sbin/xen-bugtool --yestoall --silent --output=tar --outfd="+str(file.fileno()) + ' )' - status, output = commands.getstatusoutput(command) + status, output = subprocess.getstatusoutput(command) file.close() if status != 0: 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/XSFeatureUploadBugReport.py b/plugins-base/XSFeatureUploadBugReport.py index a469f0c..6d3b8f5 100644 --- a/plugins-base/XSFeatureUploadBugReport.py +++ b/plugins-base/XSFeatureUploadBugReport.py @@ -16,6 +16,8 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") +import subprocess + from XSConsoleStandard import * class UploadBugReportDialogue(InputDialogue): @@ -46,7 +48,7 @@ def HandleCommit(self, inValues): if proxy != '': command += " http_proxy='"+proxy+"'" - status, output = commands.getstatusoutput(command) + status, output = subprocess.getstatusoutput(command) if status != 0: XSLogError('Upload bugreport failed', output) # Error output can be verbose, so syslog only diff --git a/plugins-oem/XSFeatureOEMBackup.py b/plugins-oem/XSFeatureOEMBackup.py index 9c01c57..800a6ae 100644 --- a/plugins-oem/XSFeatureOEMBackup.py +++ b/plugins-oem/XSFeatureOEMBackup.py @@ -16,6 +16,8 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") +import subprocess + from XSConsoleStandard import * class OEMBackupDialogue(FileDialogue): @@ -68,7 +70,7 @@ def DoCommit(self): filename = self.vdiMount.MountedPath(self.filename) FileUtils.AssertSafePath(filename) command = "/opt/xensource/bin/xe host-backup file-name='"+filename+"' host="+hostRef - status, output = commands.getstatusoutput(command) + status, output = subprocess.getstatusoutput(command) if status != 0: raise Exception(output) diff --git a/plugins-oem/XSFeatureOEMRestore.py b/plugins-oem/XSFeatureOEMRestore.py index 67b8014..68a44b6 100644 --- a/plugins-oem/XSFeatureOEMRestore.py +++ b/plugins-oem/XSFeatureOEMRestore.py @@ -16,6 +16,8 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") +import subprocess + from XSConsoleStandard import * class OEMRestoreDialogue(FileDialogue): @@ -58,7 +60,7 @@ def DoAction(self): filename = self.vdiMount.MountedPath(self.filename) FileUtils.AssertSafePath(filename) command = "/opt/xensource/bin/xe host-restore file-name='"+filename+"' host="+hostRef - status, output = commands.getstatusoutput(command) + status, output = subprocess.getstatusoutput(command) if status != 0: raise Exception(output) diff --git a/plugins-oem/XSFeatureUpdate.py b/plugins-oem/XSFeatureUpdate.py index 21981d6..b820ea1 100644 --- a/plugins-oem/XSFeatureUpdate.py +++ b/plugins-oem/XSFeatureUpdate.py @@ -16,6 +16,8 @@ if __name__ == "__main__": raise Exception("This script is a plugin for xsconsole and cannot run independently") +import subprocess + from XSConsoleStandard import * class UpdateDialogue(FileDialogue): @@ -58,7 +60,7 @@ def DoAction(self): filename = self.vdiMount.MountedPath(self.filename) FileUtils.AssertSafePath(filename) command = "/opt/xensource/bin/xe update-upload file-name='"+filename+"' host-uuid="+hostRef - status, output = commands.getstatusoutput(command) + status, output = subprocess.getstatusoutput(command) if status != 0: raise Exception(output) diff --git a/simpleconfig.py b/simpleconfig.py index 4bd665a..b122e05 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] in string.lowercase: + 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) -