diff --git a/drivers/BaseISCSI.py b/drivers/BaseISCSI.py index 417a7ffa1..3379795ff 100755 --- a/drivers/BaseISCSI.py +++ b/drivers/BaseISCSI.py @@ -18,6 +18,7 @@ # ISCSISR: ISCSI software initiator SR driver # +from __future__ import print_function import SR, util import time, LUNperVDI import os, sys, re, glob @@ -101,7 +102,7 @@ def _synchroniseAddrList(self, addrlist): if not self.multihomed: return change = False - if not self.dconf.has_key('multihomelist'): + if 'multihomelist' not in self.dconf: change = True self.mlist = [] mstr = "" @@ -119,7 +120,7 @@ def _synchroniseAddrList(self, addrlist): pbd = None try: pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref) - if pbd <> None: + if pbd != None: device_config = self.session.xenapi.PBD.get_device_config(pbd) device_config['multihomelist'] = mstr self.session.xenapi.PBD.set_device_config(pbd, device_config) @@ -136,13 +137,13 @@ def load(self, sr_uuid): self.default_vdi_visibility = False # Required parameters - if not self.dconf.has_key('target') or not self.dconf['target']: + if 'target' not in self.dconf or not self.dconf['target']: raise xs_errors.XenError('ConfigTargetMissing') # we are no longer putting hconf in the xml. # Instead we pass a session and host ref and let the SM backend query XAPI itself try: - if not self.dconf.has_key('localIQN'): + if 'localIQN' not in self.dconf: self.localIQN = self.session.xenapi.host.get_other_config(self.host_ref)['iscsi_iqn'] else: self.localIQN = self.dconf['localIQN'] @@ -159,16 +160,16 @@ def load(self, sr_uuid): raise xs_errors.XenError('DNSError') self.targetlist = self.target - if self.dconf.has_key('targetlist'): + if 'targetlist' in self.dconf: self.targetlist = self.dconf['targetlist'] # Optional parameters self.chapuser = "" self.chappassword = "" - if self.dconf.has_key('chapuser') \ - and (self.dconf.has_key('chappassword') or self.dconf.has_key('chappassword_secret')): + if 'chapuser' in self.dconf \ + and ('chappassword' in self.dconf or 'chappassword_secret' in self.dconf): self.chapuser = self.dconf['chapuser'].encode('utf-8') - if self.dconf.has_key('chappassword_secret'): + if 'chappassword_secret' in self.dconf: self.chappassword = util.get_secret(self.session, self.dconf['chappassword_secret']) else: self.chappassword = self.dconf['chappassword'] @@ -177,10 +178,10 @@ def load(self, sr_uuid): self.incoming_chapuser = "" self.incoming_chappassword = "" - if self.dconf.has_key('incoming_chapuser') \ - and (self.dconf.has_key('incoming_chappassword') or self.dconf.has_key('incoming_chappassword_secret')): + if 'incoming_chapuser' in self.dconf \ + and ('incoming_chappassword' in self.dconf or 'incoming_chappassword_secret' in self.dconf): self.incoming_chapuser = self.dconf['incoming_chapuser'].encode('utf-8') - if self.dconf.has_key('incoming_chappassword_secret'): + if 'incoming_chappassword_secret' in self.dconf: self.incoming_chappassword = util.get_secret(self.session, self.dconf['incoming_chappassword_secret']) else: self.incoming_chappassword = self.dconf['incoming_chappassword'] @@ -188,7 +189,7 @@ def load(self, sr_uuid): self.incoming_chappassword = self.incoming_chappassword.encode('utf-8') self.port = DEFAULT_PORT - if self.dconf.has_key('port') and self.dconf['port']: + if 'port' in self.dconf and self.dconf['port']: try: self.port = long(self.dconf['port']) except: @@ -197,17 +198,17 @@ def load(self, sr_uuid): raise xs_errors.XenError('ISCSIPort') # For backwards compatibility - if self.dconf.has_key('usediscoverynumber'): + if 'usediscoverynumber' in self.dconf: self.discoverentry = self.dconf['usediscoverynumber'] self.multihomed = False - if self.dconf.has_key('multihomed'): + if 'multihomed' in self.dconf: if self.dconf['multihomed'] == "true": self.multihomed = True elif self.mpath == 'true': self.multihomed = True - if not self.dconf.has_key('targetIQN') or not self.dconf['targetIQN']: + if 'targetIQN' not in self.dconf or not self.dconf['targetIQN']: self._scan_IQNs() raise xs_errors.XenError('ConfigTargetIQNMissing') @@ -261,7 +262,7 @@ def _initPaths(self): if not os.path.exists(self.path): # Try to detect an active path in order of priority for key in self.pathdict: - if self.adapter.has_key(key): + if key in self.adapter: self._tgtidx = key self._path = self.pathdict[self.tgtidx]['path'] if os.path.exists(self.path): @@ -303,7 +304,7 @@ def attach(self, sr_uuid): if not self.attached or multiTargets: # Verify iSCSI target and port - if self.dconf.has_key('multihomelist') and not self.dconf.has_key('multiSession'): + if 'multihomelist' in self.dconf and 'multiSession' not in self.dconf: targetlist = self.dconf['multihomelist'].split(',') else: targetlist = ['%s:%d' % (self.target,self.port)] @@ -358,7 +359,7 @@ def attach(self, sr_uuid): self.incoming_chappassword, self.mpath == "true") npaths = npaths + 1 - except Exception, e: + except Exception as e: # Exceptions thrown in login are acknowledged, # the rest of exceptions are ignored since some of the # paths in multipath may not be reachable @@ -374,14 +375,14 @@ def attach(self, sr_uuid): # Allow the devices to settle time.sleep(5) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('ISCSILogin', \ opterr='code is %d' % inst.code) self.attached = True self._initPaths() util._incr_iscsiSR_refcount(self.targetIQN, sr_uuid) IQNs = [] - if self.dconf.has_key("multiSession"): + if "multiSession" in self.dconf: IQNs = "" for iqn in self.dconf['multiSession'].split("|"): if len(iqn): IQNs += iqn.split(',')[2] @@ -406,7 +407,7 @@ def attach(self, sr_uuid): self.session.xenapi.PBD.add_to_other_config( pbdref, "iscsi_sessions", str(sessions)) - if self.dconf.has_key('SCSIid'): + if 'SCSIid' in self.dconf: if self.mpath == 'true': self.mpathmodule.refresh(self.dconf['SCSIid'], 0) devs = os.listdir("/dev/disk/by-scsid/%s" % self.dconf['SCSIid']) @@ -421,12 +422,12 @@ def detach(self, sr_uuid, delete=False): pbdref = util.find_my_pbd(self.session, self.host_ref, self.sr_ref) except: pass - if self.dconf.has_key('SCSIid'): + if 'SCSIid' in self.dconf: self.mpathmodule.reset(self.dconf['SCSIid'], explicit_unmap=True) keys.append("mpath-" + self.dconf['SCSIid']) # Remove iscsi_sessions and multipathed keys - if pbdref <> None: + if pbdref != None: if self.cmd == 'sr_detach': keys += ["multipathed", "iscsi_sessions", "MPPEnabled"] for key in keys: @@ -446,7 +447,7 @@ def detach(self, sr_uuid, delete=False): iscsilib.logout(self.target, self.targetIQN, all=True) if delete: iscsilib.delete(self.targetIQN) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('ISCSIQueryDaemon', \ opterr='error is %d' % inst.code) if iscsilib._checkTGT(self.targetIQN): @@ -461,7 +462,7 @@ def create(self, sr_uuid, size): for sr in SRs: record = SRs[sr] sm_config = record["sm_config"] - if sm_config.has_key('targetIQN') and \ + if 'targetIQN' in sm_config and \ sm_config['targetIQN'] == self.targetIQN: raise xs_errors.XenError('SRInUse') self.attach(sr_uuid) @@ -494,7 +495,7 @@ def probe(self): for sr in SRs: record = SRs[sr] sm_config = record["sm_config"] - if sm_config.has_key('targetIQN') and \ + if 'targetIQN' in sm_config and \ sm_config['targetIQN'] == self.targetIQN: Recs[record["uuid"]] = sm_config return self.srlist_toxml(Recs) @@ -535,7 +536,7 @@ def _attach_LUN_bylunid(self, lunid): raise xs_errors.XenError('SRUnavailable') connected = [] for val in self.adapter: - if not self.pathdict.has_key(val): + if val not in self.pathdict: continue rec = self.pathdict[val] path = os.path.join(rec['path'],"LUN%s" % lunid) @@ -544,7 +545,7 @@ def _attach_LUN_bylunid(self, lunid): l = [realpath, host, 0, 0, lunid] addDevice = True - if self.devs.has_key(realpath): + if realpath in self.devs: # if the device is stale remove it before adding again real_SCSIid = None try: @@ -582,12 +583,12 @@ def _attach_LUN_byserialid(self, serialid): raise xs_errors.XenError('SRUnavailable') connected = [] for val in self.adapter: - if not self.pathdict.has_key(val): + if val not in self.pathdict: continue rec = self.pathdict[val] path = os.path.join(rec['path'],"SERIAL-%s" % serialid) realpath = os.path.realpath(path) - if not self.devs.has_key(realpath): + if realpath not in self.devs: if not util.wait_for_path(path, 5): util.SMlog("Unable to detect LUN attached to host on serial path [%s]" % path) continue @@ -601,12 +602,12 @@ def _detach_LUN_bylunid(self, lunid, SCSIid): self.mpathmodule.reset(SCSIid, explicit_unmap=True) util.remove_mpathcount_field(self.session, self.host_ref, self.sr_ref, SCSIid) for val in self.adapter: - if not self.pathdict.has_key(val): + if val not in self.pathdict: continue rec = self.pathdict[val] path = os.path.join(rec['path'],"LUN%s" % lunid) realpath = os.path.realpath(path) - if self.devs.has_key(realpath): + if realpath in self.devs: util.SMlog("Found key: %s" % realpath) scsiutil.scsi_dev_ctrl(self.devs[realpath], 'remove') # Wait for device to disappear @@ -653,7 +654,7 @@ def refresh(self): # Helper function for LUN-per-VDI VDI.introduce def _getLUNbySMconfig(self, sm_config): - if not sm_config.has_key('LUNid'): + if 'LUNid' not in sm_config: raise xs_errors.XenError('VDIUnavailable') LUNid = long(sm_config['LUNid']) if not len(self._attach_LUN_bylunid(LUNid)): @@ -713,7 +714,7 @@ def print_entries(self, map): textnode = dom.createTextNode(str(iqn)) subentry.appendChild(textnode) count += 1 - print >>sys.stderr,dom.toprettyxml() + print(dom.toprettyxml(), file=sys.stderr) def srlist_toxml(self, SRs): dom = xml.dom.minidom.Document() diff --git a/drivers/DummySR.py b/drivers/DummySR.py index bf962a43d..d581706ee 100755 --- a/drivers/DummySR.py +++ b/drivers/DummySR.py @@ -98,14 +98,14 @@ def scan(self, sr_uuid): x.utilisation = v['physical_utilisation'] self.vdis[x.uuid] = x - self.physical_size = 2000000000000L - self.physical_utilisation = 0L - self.virtual_allocation = 0L + self.physical_size = 2000000000000 + self.physical_utilisation = 0 + self.virtual_allocation = 0 return super(DummySR, self).scan(sr_uuid) def _assertValues(self, vals): for attr in vals: - assert(self.srcmd.params.has_key(attr)) + assert(attr in self.srcmd.params) util.SMlog("%s param %s: [%s]" % (self.cmd,attr,self.srcmd.params[attr])) # Iterate through the device_config dictionary diff --git a/drivers/EXTSR.py b/drivers/EXTSR.py index 3eeffa3ef..1475f8a26 100755 --- a/drivers/EXTSR.py +++ b/drivers/EXTSR.py @@ -57,7 +57,7 @@ def load(self, sr_uuid): self.ops_exclusive = FileSR.OPS_EXCLUSIVE self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid) self.sr_vditype = SR.DEFAULT_TAP - if not self.dconf.has_key('device') or not self.dconf['device']: + if 'device' not in self.dconf or not self.dconf['device']: raise xs_errors.XenError('ConfigDeviceMissing') self.root = self.dconf['device'] @@ -82,7 +82,7 @@ def delete(self, sr_uuid): if txt.find(self.vgname) == -1: raise xs_errors.XenError('VolNotFound', \ opterr='volume is %s' % self.vgname) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('PVSfailed', \ opterr='error is %d' % inst.code) @@ -97,7 +97,7 @@ def delete(self, sr_uuid): for dev in self.root.split(','): cmd = ["pvremove", dev] util.pread2(cmd) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMDelete', \ opterr='errno is %d' % inst.code) @@ -111,13 +111,13 @@ def attach(self, sr_uuid): # make a mountpoint: if not os.path.isdir(self.path): os.makedirs(self.path) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMMount', \ opterr='Unable to activate LV. Errno is %d' % inst.code) try: util.pread(["fsck", "-a", self.remotepath]) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code == 1: util.SMlog("FSCK detected and corrected FS errors. Not fatal.") else: @@ -126,7 +126,7 @@ def attach(self, sr_uuid): try: util.pread(["mount", self.remotepath, self.path]) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMMount', \ opterr='Failed to mount FS. Errno is %d' % inst.code) @@ -145,7 +145,7 @@ def detach(self, sr_uuid): # deactivate SR cmd = ["lvchange", "-an", self.remotepath] util.pread2(cmd) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMUnMount', \ opterr='lvm -an failed errno is %d' % inst.code) @@ -194,7 +194,7 @@ def create(self, sr_uuid, size): cmd = ["lvchange", "-ay", self.remotepath] text = util.pread(cmd) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMCreate', \ opterr='lv operation, error %d' % inst.code) except AssertionError: @@ -203,7 +203,7 @@ def create(self, sr_uuid, size): try: util.pread2(["mkfs.ext4", "-F", self.remotepath]) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMFilesystem', \ opterr='mkfs failed error %d' % inst.code) diff --git a/drivers/FileSR.py b/drivers/FileSR.py index 5c5e97087..c98a60995 100755 --- a/drivers/FileSR.py +++ b/drivers/FileSR.py @@ -17,6 +17,7 @@ # # FileSR: local-file storage repository +from __future__ import print_function import SR, VDI, SRCommand, util, scsiutil, vhdutil import os import errno @@ -89,7 +90,7 @@ def load(self, sr_uuid): self.ops_exclusive = OPS_EXCLUSIVE self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid) self.sr_vditype = vhdutil.VDI_TYPE_VHD - if not self.dconf.has_key('location') or not self.dconf['location']: + if 'location' not in self.dconf or not self.dconf['location']: raise xs_errors.XenError('ConfigLocationMissing') self.remotepath = self.dconf['location'] self.path = os.path.join(SR.MOUNT_BASE, sr_uuid) @@ -110,7 +111,7 @@ def create(self, sr_uuid, size): else: try: util.ioretry(lambda: os.mkdir(self.remotepath)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code == errno.EEXIST: raise xs_errors.XenError('SRExists') else: @@ -140,14 +141,14 @@ def delete(self, sr_uuid): fullpath = os.path.join(self.path,name) try: util.ioretry(lambda: os.unlink(fullpath)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.ENOENT and \ inst.code != errno.EISDIR: raise xs_errors.XenError('FileSRDelete', \ opterr='failed to remove %s error %d' \ % (fullpath, inst.code)) self.detach(sr_uuid) - except util.CommandException, inst: + except util.CommandException as inst: self.detach(sr_uuid) raise xs_errors.XenError('FileSRDelete', \ opterr='error %d' % inst.code) @@ -156,13 +157,13 @@ def attach(self, sr_uuid): if not self._checkmount(): try: util.ioretry(lambda: util.makedirs(self.path)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.EEXIST: raise xs_errors.XenError("FileSRCreate", \ opterr='fail to create mount point. Errno is %s' % inst.code) try: util.pread(["mount", "--bind", self.remotepath, self.path]) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('FileSRCreate', \ opterr='fail to mount FileSR. Errno is %s' % inst.code) self.attached = True @@ -175,7 +176,7 @@ def detach(self, sr_uuid): os.chdir(SR.MOUNT_BASE) util.pread(["umount", self.path]) os.rmdir(self.path) - except Exception, e: + except Exception as e: raise xs_errors.XenError('SRInUse', opterr=str(e)) self.attached = False @@ -255,7 +256,7 @@ def _loadvdis(self): pattern = os.path.join(self.path, "*%s" % vhdutil.FILE_EXTN_VHD) try: self.vhds = vhdutil.getAllVHDs(pattern, FileVDI.extractUuid) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('SRScan', opterr="error VHD-scanning " \ "path %s (%s)" % (self.path, inst)) try: @@ -284,7 +285,7 @@ def _loadvdis(self): cbt_uuid = fn.split(".")[0] # If an associated disk exists, update CBT status # else create new VDI of type cbt_metadata - if self.vdis.has_key(cbt_uuid): + if cbt_uuid in self.vdis: self.vdis[cbt_uuid].cbt_enabled = True else: new_vdi = self.vdi(cbt_uuid) @@ -296,9 +297,9 @@ def _loadvdis(self): self.virtual_allocation = 0 for uuid, vdi in self.vdis.iteritems(): if vdi.parent: - if self.vdis.has_key(vdi.parent): + if vdi.parent in self.vdis: self.vdis[vdi.parent].read_only = True - if geneology.has_key(vdi.parent): + if vdi.parent in geneology: geneology[vdi.parent].append(uuid) else: geneology[vdi.parent] = [uuid] @@ -311,7 +312,7 @@ def _loadvdis(self): # SR.scan, so if we don't ignore hidden leaves we would pick up # freshly-deleted VDIs as newly-added VDIs for uuid in self.vdis.keys(): - if not geneology.has_key(uuid) and self.vdis[uuid].hidden: + if uuid not in geneology and self.vdis[uuid].hidden: util.SMlog("Scan found hidden leaf (%s), ignoring" % uuid) del self.vdis[uuid] @@ -336,7 +337,7 @@ def _replay(self, logentry): args.append(item) ret = cmd(*args) if ret: - print ret + print(ret) def _compare_args(self, a, b): try: @@ -381,7 +382,7 @@ def _kickGC(self): if not cleanup.abort(self.uuid, soft=True): util.SMlog("The GC has already been scheduled to " "re-start") - except util.CommandException, e: + except util.CommandException as e: if e.code != errno.ETIMEDOUT: raise util.SMlog('failed to abort the GC') @@ -460,11 +461,11 @@ def load(self, vdi_uuid): if self.sr.srcmd.cmd == "vdi_create": self.vdi_type = vhdutil.VDI_TYPE_VHD self.key_hash = None - if self.sr.srcmd.params.has_key("vdi_sm_config"): - if self.sr.srcmd.params["vdi_sm_config"].has_key("key_hash"): + if "vdi_sm_config" in self.sr.srcmd.params: + if "key_hash" in self.sr.srcmd.params["vdi_sm_config"]: self.key_hash = self.sr.srcmd.params["vdi_sm_config"]["key_hash"] - if self.sr.srcmd.params["vdi_sm_config"].has_key("type"): + if "type" in self.sr.srcmd.params["vdi_sm_config"]: vdi_type = self.sr.srcmd.params["vdi_sm_config"]["type"] if not self.VDI_TYPE.get(vdi_type): raise xs_errors.XenError('VDIType', @@ -518,7 +519,7 @@ def load(self, vdi_uuid): st = util.ioretry(lambda: os.stat(self.path), errlist=[errno.EIO, errno.ENOENT]) self.utilisation = long(st.st_size) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code == errno.EIO: raise xs_errors.XenError('VDILoad', \ opterr='Failed load VDI information %s' % self.path) @@ -546,7 +547,7 @@ def load(self, vdi_uuid): lambda: self._query_info(self.path, True), errlist=[errno.EIO, errno.ENOENT]) - if diskinfo.has_key('parent'): + if 'parent' in diskinfo: self.parent = diskinfo['parent'] self.sm_config_override = {'vhd-parent':self.parent} else: @@ -557,7 +558,7 @@ def load(self, vdi_uuid): if self.hidden: self.managed = False self.exists = True - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('VDILoad', \ opterr='Failed load VDI information %s' % self.path) @@ -586,11 +587,11 @@ def create(self, sr_uuid, vdi_uuid, size): if self.vdi_type == vhdutil.VDI_TYPE_VHD: try: size = vhdutil.validate_and_round_vhd_size(long(size)) - mb = 1024L * 1024L + mb = 1024 * 1024 size_mb = long(size) / mb util.ioretry(lambda: self._create(str(size_mb), self.path)) self.size = util.ioretry(lambda: self._query_v(self.path)) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('VDICreate', opterr='error %d' % inst.code) else: @@ -619,7 +620,7 @@ def delete(self, sr_uuid, vdi_uuid, data_only = False): try: util.force_unlink(self.path) - except Exception, e: + except Exception as e: raise xs_errors.XenError( 'VDIDelete', opterr='Failed to unlink file during deleting VDI: %s' % str(e)) @@ -654,7 +655,7 @@ def attach(self, sr_uuid, vdi_uuid): # pool database. self.xenstore_data['storage-type']='ext' return super(FileVDI, self).attach(sr_uuid, vdi_uuid) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('VDILoad', opterr='error %d' % inst.code) def detach(self, sr_uuid, vdi_uuid): @@ -896,13 +897,13 @@ def _snapshot(self, snap_type, cbtlog=None, cbt_consistency=None): sm_config = self.session.xenapi.VDI.get_sm_config(vdi_ref) sm_config['vhd-parent'] = srcparent self.session.xenapi.VDI.set_sm_config(vdi_ref, sm_config) - except Exception, e: + except Exception as e: util.SMlog("vdi_clone: caught error during VDI.db_introduce: %s" % (str(e))) # Note it's too late to actually clean stuff up here: the base disk has # been marked as deleted already. util.end_log_entry(self.sr.path, self.path, ["error"]) raise - except util.CommandException, inst: + except util.CommandException as inst: # XXX: it might be too late if the base disk has been marked as deleted! self._clonecleanup(src,dst,newsrc) util.end_log_entry(self.sr.path, self.path, ["error"]) @@ -943,12 +944,12 @@ def _clonecleanup(self,src,dst,newsrc): try: if dst: util.ioretry(lambda: os.unlink(dst)) - except util.CommandException, inst: + except util.CommandException as inst: pass try: if util.ioretry(lambda: util.pathexists(newsrc)): util.ioretry(lambda: os.rename(newsrc,src)) - except util.CommandException, inst: + except util.CommandException as inst: pass def _checkpath(self, path): @@ -956,7 +957,7 @@ def _checkpath(self, path): if not util.ioretry(lambda: util.pathexists(path)): return False return True - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('EIO', \ opterr='IO error checking path %s' % path) @@ -1057,7 +1058,7 @@ def _delete_cbt_log(self): def _rename(self, oldName, newName): try: util.ioretry(lambda: os.rename(oldName, newName)) - except util.CommandException, inst: + except util.CommandException as inst: pass def _cbt_log_exists(self, logpath): diff --git a/drivers/HBASR.py b/drivers/HBASR.py index 8496db0b7..8482f57ec 100755 --- a/drivers/HBASR.py +++ b/drivers/HBASR.py @@ -52,7 +52,7 @@ def handles(type): def load(self, sr_uuid): self.sr_vditype = 'phy' self.type = "any" - if self.dconf.has_key('type') and self.dconf['type']: + if 'type' in self.dconf and self.dconf['type']: self.type = self.dconf['type'] self.attached = False self.procname = "" @@ -181,7 +181,7 @@ def create(self, sr_uuid, size): for sr in SRs: record = SRs[sr] sm_config = record["sm_config"] - if sm_config.has_key('datatype') and \ + if 'datatype' in sm_config and \ sm_config['datatype'] == 'HBA' and \ sm_config['hbatype'] == self.type: raise xs_errors.XenError('SRInUse') @@ -216,7 +216,7 @@ def probe(self): for sr in SRs: record = SRs[sr] sm_config = record["sm_config"] - if sm_config.has_key('datatype') and \ + if 'datatype' in sm_config and \ sm_config['datatype'] == 'HBA': Recs[record["uuid"]] = sm_config return self.srlist_toxml(Recs) @@ -251,7 +251,7 @@ def _loadvdis(self): count = 0 for key in self.hbadict.iterkeys(): vdi_path = os.path.join("/dev",key) - if not self.devs.has_key(vdi_path): + if vdi_path not in self.devs: continue uuid = scsiutil.gen_uuid_from_string(scsiutil.getuniqueserial(vdi_path)) obj = self.vdi(uuid) diff --git a/drivers/ISOSR.py b/drivers/ISOSR.py index 5b1268370..77575f0b2 100755 --- a/drivers/ISOSR.py +++ b/drivers/ISOSR.py @@ -58,7 +58,7 @@ def is_image_utf8_compatible(s): if type(s) == str: try: s.decode('utf-8') - except UnicodeDecodeError, e: + except UnicodeDecodeError as e: util.SMlog("WARNING: This string is not UTF-8 compatible.") return False return True @@ -81,12 +81,12 @@ def _checkmount(self): return False try: ismount = util.ismount(self.mountpoint) - except util.CommandException, inst: + except util.CommandException as inst: return False return ismount def _checkTargetStr(self, location): - if not self.dconf.has_key('type'): + if 'type' not in self.dconf: return if self.dconf['type'] == 'cifs': tgt = '' @@ -149,7 +149,7 @@ def _loadvdis(self): if vdi.location in __xenapi_locations: v = __xenapi_records[__xenapi_locations[vdi.location]] sm_config = v['sm_config'] - if sm_config.has_key('created'): + if 'created' in sm_config: vdi.sm_config['created'] = sm_config['created'] vdi.read_only = False @@ -179,7 +179,7 @@ def vdi(self, uuid): _VDI = self.session.xenapi.VDI try: vdi_ref = _VDI.get_by_uuid(uuid) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if e.details[0] != 'UUID_INVALID': raise else: filename = _VDI.get_location(vdi_ref) @@ -187,7 +187,7 @@ def vdi(self, uuid): if filename is None: # Get the filename from sm-config['path'], or use the UUID # if the path param doesn't exist. - if smconfig and smconfig.has_key('path'): + if smconfig and 'path' in smconfig: filename = smconfig['path'] if not self.vdi_path_regex.match(filename): raise xs_errors.XenError('VDICreate', \ @@ -200,11 +200,11 @@ def vdi(self, uuid): def load(self, sr_uuid): """Initialises the SR""" # First of all, check we've got the correct keys in dconf - if not self.dconf.has_key('location'): + if 'location' not in self.dconf: raise xs_errors.XenError('ConfigLocationMissing') # Construct the path we're going to mount under: - if self.dconf.has_key("legacy_mode"): + if "legacy_mode" in self.dconf: self.mountpoint = util.to_plain_string(self.dconf['location']) else: # Verify the target address @@ -212,7 +212,7 @@ def load(self, sr_uuid): self.mountpoint = os.path.join(SR.MOUNT_BASE, sr_uuid) # Add on the iso_path value if there is one - if self.dconf.has_key("iso_path"): + if "iso_path" in self.dconf: iso_path = util.to_plain_string(self.dconf['iso_path']) if iso_path.startswith("/"): iso_path=iso_path[1:] @@ -238,7 +238,7 @@ def delete(self, sr_uuid): def attach(self, sr_uuid): """Std. attach""" # Very-Legacy mode means the ISOs are in the local fs - so no need to attach. - if self.dconf.has_key('legacy_mode'): + if 'legacy_mode' in self.dconf: # Verify path exists if not os.path.exists(self.mountpoint): raise xs_errors.XenError('ISOLocalPath') @@ -258,7 +258,7 @@ def attach(self, sr_uuid): protocol = 'nfs_iso' options = '' - if self.dconf.has_key('type'): + if 'type' in self.dconf: protocol = self.dconf['type'] elif ":/" not in location: protocol = 'cifs' @@ -275,7 +275,7 @@ def attach(self, sr_uuid): # In both cases check if SMB version is passed are not. # If not use self.smbversion. if protocol == 'cifs': - if self.dconf.has_key('type'): + if 'type' in self.dconf: # Create via XC or sr-create # Check for username and password mountcmd=["mount.cifs", location, self.mountpoint] @@ -323,7 +323,7 @@ def attach(self, sr_uuid): util.SMlog('ISOSR mount over smb 3.0') try: self.mountOverSMB(mountcmd) - except util.CommandException, inst: + except util.CommandException as inst: if not self.is_smbversion_specified: util.SMlog('Retrying ISOSR mount over smb 1.0') smb3_fail_reason = inst.reason @@ -347,7 +347,7 @@ def attach(self, sr_uuid): else: util.SMlog('ISOSR mount over smb 1.0') self.mountOverSMB(mountcmd) - except util.CommandException, inst: + except util.CommandException as inst: if not self.is_smbversion_specified: raise xs_errors.XenError( 'ISOMountFailure', opterr=smb3_fail_reason) @@ -461,7 +461,7 @@ def detach(self, sr_uuid): try: util.pread(["umount", self.mountpoint]); - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('NFSUnMount', \ opterr = 'error is %d' % inst.code) @@ -471,7 +471,7 @@ def scan(self, sr_uuid): raise xs_errors.XenError('SRUnavailable', \ opterr = 'no such directory %s' % self.path) - if (not self.dconf.has_key('legacy_mode')) and (not self._checkmount()): + if ('legacy_mode' not in self.dconf) and (not self._checkmount()): raise xs_errors.XenError('SRUnavailable', \ opterr = 'directory not mounted: %s' % self.path) @@ -484,7 +484,7 @@ def scan(self, sr_uuid): other_config = self.session.xenapi.SR.get_other_config(self.sr_ref) - if other_config.has_key('xenserver_tools_sr') and \ + if 'xenserver_tools_sr' in other_config and \ other_config['xenserver_tools_sr'] == "true": # Out of all the xs-tools ISOs which exist in this dom0, we mark # only one as the official one. @@ -499,7 +499,7 @@ def scan(self, sr_uuid): latest_build_vdi = vdi.location latest_build_number = "0" - if vdi.sm_config.has_key('xs-tools-build'): + if 'xs-tools-build' in vdi.sm_config: bld = vdi.sm_config['xs-tools-build'] if bld >= latest_build_number: latest_build_vdi = vdi.location @@ -511,7 +511,7 @@ def scan(self, sr_uuid): if vdi.location == latest_build_vdi: vdi.sm_config['xs-tools'] = "true" else: - if vdi.sm_config.has_key("xs-tools"): + if "xs-tools" in vdi.sm_config: del vdi.sm_config['xs-tools'] @@ -526,9 +526,9 @@ def scan(self, sr_uuid): all_vdis = self.session.xenapi.VDI.get_all_records_where("field \"SR\" = \"%s\"" % sr) for vdi_ref in all_vdis.keys(): vdi = all_vdis[vdi_ref] - if vdi['sm_config'].has_key('xs-tools-version'): + if 'xs-tools-version' in vdi['sm_config']: name = tools_iso_name(vdi['location']) - if vdi['sm_config'].has_key('xs-tools'): + if 'xs-tools' in vdi['sm_config']: self.session.xenapi.VDI.set_name_label(vdi_ref, name) else: self.session.xenapi.VDI.set_name_label(vdi_ref, "Old version of " + name) @@ -551,7 +551,7 @@ def scan(self, sr_uuid): def create(self, sr_uuid, size): self.attach(sr_uuid) - if self.dconf.has_key('type'): + if 'type' in self.dconf: smconfig = self.session.xenapi.SR.get_sm_config(self.sr_ref) smconfig['iso_type'] = self.dconf['type'] self.session.xenapi.SR.set_sm_config(self.sr_ref, smconfig) @@ -590,7 +590,7 @@ def __init__(self, mysr, filename): self.read_only = True self.label = filename self.sm_config = {} - if mysr.dconf.has_key("legacy_mode"): + if "legacy_mode" in mysr.dconf: if filename.startswith("xs-tools") or filename.startswith("guest-tools"): self.label = tools_iso_name(filename) # Mark this as a Tools CD @@ -626,7 +626,7 @@ def create(self, sr_uuid, vdi_uuid, size): self.uuid = vdi_uuid self.path = os.path.join(self.sr.path, self.filename) self.size = size - self.utilisation = 0L + self.utilisation = 0 self.read_only = False self.sm_config = self.sr.srcmd.params['vdi_sm_config'] self.sm_config['created'] = util._getDateString() @@ -640,7 +640,7 @@ def create(self, sr_uuid, vdi_uuid, size): handle.close() self._db_introduce() return super(ISOVDI, self).get_params() - except Exception, exn: + except Exception as exn: util.SMlog("Exception when creating VDI: %s" % exn) raise xs_errors.XenError('VDICreate', \ opterr='could not create file: "%s"' % self.path) diff --git a/drivers/LUNperVDI.py b/drivers/LUNperVDI.py index 553e7baaf..0c71fcd3e 100755 --- a/drivers/LUNperVDI.py +++ b/drivers/LUNperVDI.py @@ -83,7 +83,7 @@ def create(self, sr_uuid, vdi_uuid, size): for vdi in VDIs: if not vdi['managed'] \ and long(vdi['virtual_size']) >= long(size) \ - and self.sr.vdis.has_key(vdi['uuid']): + and vdi['uuid'] in self.sr.vdis: if not smallest: smallest = long(vdi['virtual_size']) v = vdi @@ -108,11 +108,11 @@ def delete(self, sr_uuid, vdi_uuid): def attach(self, sr_uuid, vdi_uuid): self.sr._loadvdis() - if not self.sr.vdis.has_key(vdi_uuid): + if vdi_uuid not in self.sr.vdis: raise xs_errors.XenError('VDIUnavailable') if not util.pathexists(self.path): self.sr.refresh() - if self.sm_config.has_key('SCSIid'): + if 'SCSIid' in self.sm_config: if self.sr.mpath == 'true': self.sr.mpathmodule.refresh(self.sm_config['SCSIid'], 0) devs = os.listdir("/dev/disk/by-scsid/%s" % self.sm_config['SCSIid']) @@ -126,9 +126,9 @@ def attach(self, sr_uuid, vdi_uuid): def detach(self, sr_uuid, vdi_uuid): self.sr._loadvdis() - if self.sm_config.has_key('SCSIid'): + if 'SCSIid' in self.sm_config: self.sr.mpathmodule.reset(self.sm_config['SCSIid'], True) # explicitly unmap - if not self.sr.vdis.has_key(vdi_uuid): + if vdi_uuid not in self.sr.vdis: raise xs_errors.XenError('VDIUnavailable') def _set_managed(self, vdi_uuid, managed): diff --git a/drivers/LVHDSR.py b/drivers/LVHDSR.py index b84d5ecae..4a74558d1 100755 --- a/drivers/LVHDSR.py +++ b/drivers/LVHDSR.py @@ -144,7 +144,7 @@ def handles(type): def load(self, sr_uuid): self.ops_exclusive = OPS_EXCLUSIVE - if not self.dconf.has_key('device') or not self.dconf['device']: + if 'device' not in self.dconf or not self.dconf['device']: raise xs_errors.XenError('ConfigDeviceMissing',) self.root = self.dconf['device'] for dev in self.root.split(','): @@ -153,7 +153,7 @@ def load(self, sr_uuid): opterr='path is %s' % dev) self.isMaster = False - if self.dconf.has_key('SRmaster') and self.dconf['SRmaster'] == 'true': + if 'SRmaster' in self.dconf and self.dconf['SRmaster'] == 'true': self.isMaster = True self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid) @@ -173,7 +173,7 @@ def load(self, sr_uuid): if not self.srcmd.params.get("sr_ref"): return # must be a probe call # Test for thick vs thin provisioning conf parameter - if self.dconf.has_key('allocation'): + if 'allocation' in self.dconf: if self.dconf['allocation'] in self.PROVISIONING_TYPES: self.provision = self.dconf['allocation'] else: @@ -278,7 +278,7 @@ def updateSRMetadata(self, allocation): } LVMMetadataHandler(self.mdpath).writeMetadata(sr_info, vdi_info) - except Exception, e: + except Exception as e: raise xs_errors.XenError('MetadataError', \ opterr='Error upgrading SR Metadata: %s' % str(e)) @@ -310,7 +310,7 @@ def syncMetadataAndStorage(self): # This should never happen pass - except Exception, e: + except Exception as e: raise xs_errors.XenError('MetadataError', \ opterr='Error synching SR Metadata and storage: %s' % str(e)) @@ -349,7 +349,7 @@ def syncMetadataAndXapi(self): update_map[NAME_DESCRIPTION_TAG] = new_name_description LVMMetadataHandler(self.mdpath)\ .updateMetadata(update_map) - except Exception, e: + except Exception as e: raise xs_errors.XenError('MetadataError', \ opterr='Error synching SR Metadata and XAPI: %s' % str(e)) @@ -374,7 +374,7 @@ def _checkMetadataVolume(self): util.SMlog("Sync SR metadata and the state on the storage.") self.syncMetadataAndStorage() self.syncMetadataAndXapi() - except Exception, e: + except Exception as e: util.SMlog("Exception in _checkMetadataVolume, " \ "Error: %s." % str(e)) elif not self.mdexists and not self.legacyMode: @@ -396,7 +396,7 @@ def _synchSmConfigWithMetaData(self): # from pre-6.0 pools xml = retrieveXMLfromFile(self.mdpath) sr_info = _parseXML(xml) - except Exception, e: + except Exception as e: # That dint work, try new format valid 6.0 onwards util.SMlog("Could not read SR info from metadata using old " \ "format, trying new format. Error: %s" % str(e)) @@ -405,14 +405,14 @@ def _synchSmConfigWithMetaData(self): if sr_info == {}: raise Exception("Failed to get SR information from metadata.") - if sr_info.has_key("allocation"): + if "allocation" in sr_info: self.provision = sr_info.get("allocation") map['allocation'] = sr_info.get("allocation") else: raise Exception("Allocation key not found in SR metadata. " \ "SR info found: %s" % sr_info) - except Exception, e: + except Exception as e: raise xs_errors.XenError('MetadataError', \ opterr='Error reading SR params from ' \ 'metadata Volume: %s' % str(e)) @@ -442,7 +442,7 @@ def _introduceMetaDataVolume(self): # Add the SR metadata self.updateSRMetadata(self.provision) - except Exception, e: + except Exception as e: raise xs_errors.XenError('MetadataError', \ opterr='Error introducing Metadata Volume: %s' % str(e)) @@ -552,7 +552,7 @@ def delete(self, uuid): replace('//', '-')) lpath = os.path.join(self.path, lvname) os.unlink(lpath) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: util.SMlog("LVHDSR.delete: failed to remove the symlink for " \ "file %s. Error: %s" % (fileName, str(e))) @@ -562,7 +562,7 @@ def delete(self, uuid): try: if util.pathexists(self.path): os.rmdir(self.path) - except Exception, e: + except Exception as e: util.SMlog("LVHDSR.delete: failed to remove the symlink " \ "directory %s. Error: %s" % (self.path, str(e))) success = False @@ -643,7 +643,7 @@ def detach(self, uuid): replace('//', '-')) lvname = os.path.join(self.path, lvname) util.force_unlink(lvname) - except Exception, e: + except Exception as e: util.SMlog("LVHDSR.detach: failed to remove the symlink for " \ "file %s. Error: %s" % (fileName, str(e))) success = False @@ -654,7 +654,7 @@ def detach(self, uuid): try: if util.pathexists(self.path): os.rmdir(self.path) - except Exception, e: + except Exception as e: util.SMlog("LVHDSR.detach: failed to remove the symlink " \ "directory %s. Error: %s" % (self.path, str(e))) success = False @@ -707,7 +707,7 @@ def scan(self, uuid): for vdi in Dict.keys(): vdi_uuid = Dict[vdi][UUID_TAG] if bool(int(Dict[vdi][IS_A_SNAPSHOT_TAG])): - if vdiToSnaps.has_key(Dict[vdi][SNAPSHOT_OF_TAG]): + if Dict[vdi][SNAPSHOT_OF_TAG] in vdiToSnaps: vdiToSnaps[Dict[vdi][SNAPSHOT_OF_TAG]].append(vdi_uuid) else: vdiToSnaps[Dict[vdi][SNAPSHOT_OF_TAG]] = [vdi_uuid] @@ -782,7 +782,7 @@ def scan(self, uuid): # For existing VDIs, update local state too # Scan in base class SR updates existing VDIs # again based on local states - if self.vdis.has_key(vdi_uuid): + if vdi_uuid in self.vdis: self.vdis[vdi_uuid].cbt_enabled = True cbt_vdis.remove(cbt_logname) @@ -800,7 +800,7 @@ def scan(self, uuid): snapref = \ self.session.xenapi.VDI.get_by_uuid(snapvdi) self.session.xenapi.VDI.set_snapshot_of(snapref, srcref) - except Exception, e: + except Exception as e: util.SMlog("Setting snapshot failed. "\ "Error: %s" % str(e)) @@ -856,7 +856,7 @@ def probe(self): return lvutil.srlist_toxml( lvutil.scan_srlist(lvhdutil.VG_PREFIX, self.root), lvhdutil.VG_PREFIX, - (self.srcmd.params['sr_sm_config'].has_key('metadata') and \ + ('metadata' in self.srcmd.params['sr_sm_config'] and \ self.srcmd.params['sr_sm_config']['metadata'] == 'true')) def vdi(self, uuid): @@ -879,9 +879,9 @@ def _loadvdis(self): for uuid, vdi in self.vdis.iteritems(): if vdi.parent: - if self.vdis.has_key(vdi.parent): + if vdi.parent in self.vdis: self.vdis[vdi.parent].read_only = True - if geneology.has_key(vdi.parent): + if vdi.parent in geneology: geneology[vdi.parent].append(uuid) else: geneology[vdi.parent] = [uuid] @@ -889,7 +889,7 @@ def _loadvdis(self): # Now remove all hidden leaf nodes to avoid introducing records that # will be GC'ed for uuid in self.vdis.keys(): - if not geneology.has_key(uuid) and self.vdis[uuid].hidden: + if uuid not in geneology and self.vdis[uuid].hidden: util.SMlog("Scan found hidden leaf (%s), ignoring" % uuid) del self.vdis[uuid] @@ -1320,7 +1320,7 @@ def _kickGC(self): if not cleanup.abort(self.uuid, soft=True): util.SMlog("The GC has already been scheduled to " "re-start") - except util.CommandException, e: + except util.CommandException as e: if e.code != errno.ETIMEDOUT: raise util.SMlog('failed to abort the GC') @@ -1367,8 +1367,8 @@ def load(self, vdi_uuid): # the VDI must be in the process of being created self.exists = False - if self.sr.srcmd.params.has_key("vdi_sm_config") and \ - self.sr.srcmd.params["vdi_sm_config"].has_key("type"): + if "vdi_sm_config" in self.sr.srcmd.params and \ + "type" in self.sr.srcmd.params["vdi_sm_config"]: type = self.sr.srcmd.params["vdi_sm_config"]["type"] if type == PARAM_RAW: self.vdi_type = vhdutil.VDI_TYPE_RAW @@ -1414,7 +1414,7 @@ def create(self, sr_uuid, vdi_uuid, size): vhdutil.create(self.path, long(size), False, lvhdutil.MSIZE_MB) self.size = vhdutil.getSizeVirt(self.path) self.sr.lvmCache.deactivateNoRefcount(self.lvname) - except util.CommandException, e: + except util.CommandException as e: util.SMlog("Unable to create VDI"); self.sr.lvmCache.remove(self.lvname) raise xs_errors.XenError('VDICreate', opterr='error %d' % e.code) @@ -1450,7 +1450,7 @@ def delete(self, sr_uuid, vdi_uuid, data_only = False): util.SMlog("LVHDVDI.delete for %s" % self.uuid) try: self._loadThis() - except SR.SRException, e: + except SR.SRException as e: # Catch 'VDI doesn't exist' exception if e.errno == 46: return super(LVHDVDI, self).delete(sr_uuid, vdi_uuid, data_only) @@ -1482,7 +1482,7 @@ def delete(self, sr_uuid, vdi_uuid, data_only = False): self.sr.lvmCache.remove(self.lvname) self.sr.lock.cleanup(vdi_uuid, lvhdutil.NS_PREFIX_LVM + sr_uuid) self.sr.lock.cleanupAll(vdi_uuid) - except SR.SRException, e: + except SR.SRException as e: util.SMlog( "Failed to remove the volume (maybe is leaf coalescing) " "for %s err:%d" % (self.uuid, e.errno)) @@ -1688,11 +1688,11 @@ def _do_snapshot(self, sr_uuid, vdi_uuid, snapType, snapResult = None try: snapResult = self._snapshot(snapType, cloneOp, cbtlog, consistency_state) - except Exception, e1: + except Exception as e1: try: blktap2.VDI.tap_unpause(self.session, sr_uuid, vdi_uuid, secondary=None) - except Exception, e2: + except Exception as e2: util.SMlog('WARNING: failed to clean up failed snapshot: ' '%s (error ignored)' % e2) raise @@ -1713,7 +1713,7 @@ def _snapshot(self, snapType, cloneOp = False, cbtlog = None, cbt_consistency = self.sm_config = self.session.xenapi.VDI.get_sm_config( \ self.sr.srcmd.params['vdi_ref']) - if self.sm_config.has_key("type") and self.sm_config['type']=='raw': + if "type" in self.sm_config and self.sm_config['type']=='raw': if not util.fistpoint.is_active("testsm_clone_allow_raw"): raise xs_errors.XenError('Unimplemented', \ opterr='Raw VDI, snapshot or clone not permitted') @@ -1845,7 +1845,7 @@ def _snapshot(self, snapType, cloneOp = False, cbtlog = None, cbt_consistency = snapVDI._disable_cbt_on_error(alert_name, alert_str) pass - except (util.SMException, XenAPI.Failure), e: + except (util.SMException, XenAPI.Failure) as e: util.logException("LVHDVDI._snapshot") self._failClone(origUuid, jval, str(e)) util.fistpoint.activate("LVHDRT_clone_vdi_before_remove_journal",self.sr.uuid) @@ -2061,7 +2061,7 @@ def _initFromVHDInfo(self, vhdInfo): def _determineType(self): """Determine whether this is a raw or a VHD VDI""" - if self.sr.srcmd.params.has_key("vdi_ref"): + if "vdi_ref" in self.sr.srcmd.params: vdi_ref = self.sr.srcmd.params["vdi_ref"] sm_config = self.session.xenapi.VDI.get_sm_config(vdi_ref) if sm_config.get("vdi_type"): @@ -2109,7 +2109,7 @@ def _loadThis(self): return try: lvs = lvhdutil.getLVInfo(self.sr.lvmCache, self.lvname) - except util.CommandException, e: + except util.CommandException as e: raise xs_errors.XenError('VDIUnavailable', opterr= '%s (LV scan error)' % os.strerror(abs(e.code))) if not lvs.get(self.uuid): @@ -2152,7 +2152,7 @@ def _failClone(self, uuid, jval, msg): try: self.sr._handleInterruptedCloneOp(uuid, jval, True) self.sr.journaler.remove(self.JRN_CLONE, uuid) - except Exception, e: + except Exception as e: util.SMlog('WARNING: failed to clean up failed snapshot: ' \ ' %s (error ignored)' % e) raise xs_errors.XenError('VDIClone', opterr=msg) @@ -2245,7 +2245,7 @@ def _activate_cbt_log(self, lv_name): try: self.sr.lvmCache.activateNoRefcount(lv_name) return True - except Exception, e: + except Exception as e: util.SMlog("Exception in _activate_cbt_log, " "Error: %s." % str(e)) else: @@ -2254,7 +2254,7 @@ def _activate_cbt_log(self, lv_name): def _deactivate_cbt_log(self, lv_name): try: self.sr.lvmCache.deactivateNoRefcount(lv_name) - except Exception, e: + except Exception as e: util.SMlog("Exception in _deactivate_cbt_log, Error: %s." % str(e)) def _cbt_log_exists(self, logpath): diff --git a/drivers/LVHDoFCoESR.py b/drivers/LVHDoFCoESR.py index 4875392e9..51d0238b5 100755 --- a/drivers/LVHDoFCoESR.py +++ b/drivers/LVHDoFCoESR.py @@ -18,6 +18,7 @@ # LVHDoFCoESR: LVHD over Fibre Channel over Ethernet driver # +from __future__ import print_function import SR import LVHDoHBASR import LVHDSR @@ -78,8 +79,8 @@ def load(self, sr_uuid): except: pass - if not self.dconf.has_key('SCSIid') or not self.dconf['SCSIid']: - print >>sys.stderr, self.hbasr.print_devs() + if 'SCSIid' not in self.dconf or not self.dconf['SCSIid']: + print(self.hbasr.print_devs(), file=sys.stderr) raise xs_errors.XenError('ConfigSCSIid') self.SCSIid = self.dconf['SCSIid'] diff --git a/drivers/LVHDoHBASR.py b/drivers/LVHDoHBASR.py index a71770196..a339366b0 100755 --- a/drivers/LVHDoHBASR.py +++ b/drivers/LVHDoHBASR.py @@ -19,6 +19,7 @@ # hardware based iSCSI # +from __future__ import print_function import SR, LVHDSR, SRCommand, lvutil, HBASR import os import re @@ -77,7 +78,7 @@ def load(self, sr_uuid): pass try: - if not self.dconf.has_key('SCSIid') and self.dconf.has_key('device'): + if 'SCSIid' not in self.dconf and 'device' in self.dconf: # UPGRADE FROM MIAMI: add SCSIid key to device_config util.SMlog("Performing upgrade from Miami") if not os.path.exists(self.dconf['device']): @@ -86,7 +87,7 @@ def load(self, sr_uuid): self.dconf['SCSIid'] = SCSIid del self.dconf['device'] - if pbd <> None: + if pbd != None: device_config = self.session.xenapi.PBD.get_device_config(pbd) device_config['SCSIid'] = SCSIid device_config['upgraded_from_miami'] = 'true' @@ -95,8 +96,8 @@ def load(self, sr_uuid): except: pass - if not self.dconf.has_key('SCSIid') or not self.dconf['SCSIid']: - print >>sys.stderr,self.hbasr.print_devs() + if 'SCSIid' not in self.dconf or not self.dconf['SCSIid']: + print(self.hbasr.print_devs(), file=sys.stderr) raise xs_errors.XenError('ConfigSCSIid') self.SCSIid = self.dconf['SCSIid'] @@ -148,7 +149,7 @@ def scan(self, sr_uuid): LVHDSR.LVHDSR.scan(self, sr_uuid) def probe(self): - if self.mpath == "true" and self.dconf.has_key('SCSIid'): + if self.mpath == "true" and 'SCSIid' in self.dconf: # When multipathing is enabled, since we don't refcount the multipath maps, # we should not attempt to do the iscsi.attach/detach when the map is already present, # as this will remove it (which may well be in use). diff --git a/drivers/LVHDoISCSISR.py b/drivers/LVHDoISCSISR.py index 5479eec49..5e6c02461 100755 --- a/drivers/LVHDoISCSISR.py +++ b/drivers/LVHDoISCSISR.py @@ -18,6 +18,7 @@ # LVHDoISCSISR: LVHD over ISCSI software initiator SR driver # +from __future__ import print_function import SR, LVHDSR, BaseISCSI, SRCommand, util, scsiutil, lvutil import time import os, sys @@ -81,7 +82,7 @@ def load(self, sr_uuid): if util.isVDICommand(self.original_srcmd.cmd): self.SCSIid = self.dconf['SCSIid'] else: - if self.original_srcmd.dconf.has_key('target'): + if 'target' in self.original_srcmd.dconf: self.original_srcmd.dconf['targetlist'] = self.original_srcmd.dconf['target'] iscsi = BaseISCSI.BaseISCSISR(self.original_srcmd, sr_uuid) self.iscsiSRs = [] @@ -99,7 +100,7 @@ def load(self, sr_uuid): IQNstring = "" IQNs = [] try: - if self.dconf.has_key('multiSession'): + if 'multiSession' in self.dconf: IQNs = self.dconf['multiSession'].split("|") for IQN in IQNs: if IQN: @@ -151,7 +152,7 @@ def load(self, sr_uuid): util.SMlog("Setting targetlist: %s" % srcmd_copy.dconf['targetlist']) self.iscsiSRs.append(BaseISCSI.BaseISCSISR(srcmd_copy, sr_uuid)) pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref) - if pbd <> None and not self.dconf.has_key('multiSession'): + if pbd != None and 'multiSession' not in self.dconf: dconf = self.session.xenapi.PBD.get_device_config(pbd) dconf['multiSession'] = IQNstring self.session.xenapi.PBD.set_device_config(pbd, dconf) @@ -177,7 +178,7 @@ def load(self, sr_uuid): pass # Apart from the upgrade case, user must specify a SCSIid - if not self.dconf.has_key('SCSIid'): + if 'SCSIid' not in self.dconf: # Dual controller issue self.LUNs = {} # Dict for LUNs from all the iscsi objects for ii in range(0, len(self.iscsiSRs)): @@ -296,7 +297,7 @@ def load(self, sr_uuid): iqn = self.iscsiSRs[kkk].targetIQN key = "%s,%s,%s" % (ipaddr,port,iqn) # The final string must preserve the order without repetition - if not IQNs.has_key(key): + if key not in IQNs: IQNs[key] = "" IQNstring += "%s|" % key util.SMlog("IQNstring is now %s" %IQNstring) @@ -305,7 +306,7 @@ def load(self, sr_uuid): # Updating pbd entry, if any try: pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref) - if pbd <> None and self.dconf.has_key('multiSession'): + if pbd != None and 'multiSession' in self.dconf: util.SMlog("Updating multiSession in PBD") dconf = self.session.xenapi.PBD.get_device_config(pbd) dconf['multiSession'] = IQNstring @@ -351,7 +352,7 @@ def print_LUNs_XML(self): textnode = dom.createTextNode(str(aval)) subentry.appendChild(textnode) - print >>sys.stderr,dom.toprettyxml() + print(dom.toprettyxml(), file=sys.stderr) def _getSCSIid_from_LUN(self, sr_uuid): was_attached = True @@ -467,7 +468,7 @@ def create(self, sr_uuid, size): raise xs_errors.XenError('InvalidDev') self._pathrefresh(LVHDoISCSISR) LVHDSR.LVHDSR.create(self, sr_uuid, size) - except Exception, inst: + except Exception as inst: self.iscsi.detach(sr_uuid) raise xs_errors.XenError("SRUnavailable", opterr=inst) self.iscsi.detach(sr_uuid) @@ -483,7 +484,7 @@ def attach(self, sr_uuid): for i in self.iscsiSRs: try: i.attach(sr_uuid) - except SR.SROSError, inst: + except SR.SROSError as inst: # Some iscsi objects can fail login but not all. Storing exception if inst.errno == 141: util.SMlog("Connection failed for target %s, continuing.." %i.target) @@ -501,14 +502,14 @@ def attach(self, sr_uuid): if not connected: raise stored_exception - if self.dconf.has_key('multiSession'): + if 'multiSession' in self.dconf: # Force a manual bus refresh for a in self.iscsi.adapter: scsiutil.rescan([self.iscsi.adapter[a]]) self._pathrefresh(LVHDoISCSISR) LVHDSR.LVHDSR.attach(self, sr_uuid) - except Exception, inst: + except Exception as inst: for i in self.iscsiSRs: i.detach(sr_uuid) raise xs_errors.XenError("SRUnavailable", opterr=inst) @@ -534,7 +535,7 @@ def probe(self): # When multipathing is enabled, since we don't refcount the multipath maps, # we should not attempt to do the iscsi.attach/detach when the map is already present, # as this will remove it (which may well be in use). - if self.mpath == 'true' and self.dconf.has_key('SCSIid'): + if self.mpath == 'true' and 'SCSIid' in self.dconf: maps = [] try: maps = mpath_cli.list_maps() @@ -566,7 +567,7 @@ def generate_config(self, sr_uuid, vdi_uuid): self.sr.dconf['multipathing'] = self.sr.mpath self.sr.dconf['multipathhandle'] = self.sr.mpathhandle dict['device_config'] = self.sr.dconf - if dict['device_config'].has_key('chappassword_secret'): + if 'chappassword_secret' in dict['device_config']: s = util.get_secret(self.session, dict['device_config']['chappassword_secret']) del dict['device_config']['chappassword_secret'] dict['device_config']['chappassword'] = s diff --git a/drivers/NFSSR.py b/drivers/NFSSR.py index b2a688050..634ed54de 100755 --- a/drivers/NFSSR.py +++ b/drivers/NFSSR.py @@ -17,6 +17,7 @@ # # FileSR: local-file storage repository +from __future__ import print_function import SR, SRCommand, FileSR, util import errno import os, sys @@ -72,7 +73,7 @@ def load(self, sr_uuid): self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid) self.sr_vditype = SR.DEFAULT_TAP self.driver_config = DRIVER_CONFIG - if not self.dconf.has_key('server'): + if 'server' not in self.dconf: raise xs_errors.XenError('ConfigServerMissing') self.remoteserver = self.dconf['server'] self.nosubdir = False @@ -83,14 +84,14 @@ def load(self, sr_uuid): self.sm_config = self.srcmd.params.get('sr_sm_config') or {} self.other_config = self.srcmd.params.get('sr_other_config') or {} self.nosubdir = self.sm_config.get('nosubdir') == "true" - if self.dconf.has_key('serverpath'): + if 'serverpath' in self.dconf: self.remotepath = os.path.join(self.dconf['serverpath'], not self.nosubdir and sr_uuid or "").encode('utf-8') self.path = os.path.join(SR.MOUNT_BASE, sr_uuid) # Handle optional dconf attributes self.transport = DEFAULT_TRANSPORT - if self.dconf.has_key('useUDP') and self.dconf['useUDP'] == 'true': + if 'useUDP' in self.dconf and self.dconf['useUDP'] == 'true': self.transport = "udp" self.nfsversion = nfs.validate_nfsversion(self.dconf.get('nfsversion')) if 'options' in self.dconf: @@ -100,7 +101,7 @@ def load(self, sr_uuid): def validate_remotepath(self, scan): - if not self.dconf.has_key('serverpath'): + if 'serverpath' not in self.dconf: if scan: try: self.scan_exports(self.dconf['server']) @@ -113,13 +114,13 @@ def validate_remotepath(self, scan): def check_server(self): try: - if self.dconf.has_key(PROBEVERSION): + if PROBEVERSION in self.dconf: sv = nfs.get_supported_nfs_versions(self.remoteserver) if len(sv): self.nfsversion = sv[0] else: nfs.check_server_tcp(self.remoteserver, self.nfsversion) - except nfs.NfsException, exc: + except nfs.NfsException as exc: raise xs_errors.XenError('NFSVersion', opterr=exc.errstr) @@ -130,7 +131,7 @@ def mount(self, mountpoint, remotepath, timeout=None, retrans=None): mountpoint, self.remoteserver, remotepath, self.transport, useroptions=self.options, timeout=timeout, nfsversion=self.nfsversion, retrans=retrans) - except nfs.NfsException, exc: + except nfs.NfsException as exc: raise xs_errors.XenError('NFSMount', opterr=exc.errstr) @@ -188,7 +189,7 @@ def detach(self, sr_uuid): try: nfs.unmount(self.path, True) - except nfs.NfsException, exc: + except nfs.NfsException as exc: raise xs_errors.XenError('NFSUnMount', opterr=exc.errstr) self.attached = False @@ -205,7 +206,7 @@ def create(self, sr_uuid, size): self.remotepath = self.dconf['serverpath'].encode('utf-8') try: self.mount_remotepath(sr_uuid) - except Exception, exn: + except Exception as exn: try: os.rmdir(self.path) except: @@ -221,7 +222,7 @@ def create(self, sr_uuid, size): else: try: util.ioretry(lambda: util.makedirs(newpath)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.EEXIST: self.detach(sr_uuid) raise xs_errors.XenError('NFSCreate', @@ -245,7 +246,7 @@ def delete(self, sr_uuid): if util.ioretry(lambda: util.pathexists(newpath)): util.ioretry(lambda: os.rmdir(newpath)) self.detach(sr_uuid) - except util.CommandException, inst: + except util.CommandException as inst: self.detach(sr_uuid) if inst.code != errno.ENOENT: raise xs_errors.XenError('NFSDelete') @@ -258,7 +259,7 @@ def vdi(self, uuid, loadLocked = False): def scan_exports(self, target): util.SMlog("scanning2 (target=%s)" % target) dom = nfs.scan_exports(target) - print >>sys.stderr,dom.toprettyxml() + print(dom.toprettyxml(), file=sys.stderr) class NFSFileVDI(FileSR.FileVDI): def attach(self, sr_uuid, vdi_uuid): diff --git a/drivers/OCFSSR.py b/drivers/OCFSSR.py index 151002e26..c652aa90e 100755 --- a/drivers/OCFSSR.py +++ b/drivers/OCFSSR.py @@ -57,7 +57,7 @@ def handles(type): def load(self, sr_uuid): - if not self.dconf.has_key('device') or not self.dconf['device']: + if 'device' not in self.dconf or not self.dconf['device']: raise xs_errors.XenError('ConfigDeviceMissing',) self.blockdevice = self.dconf['device'] if not self._isvalidpathstring(self.blockdevice): @@ -65,7 +65,7 @@ def load(self, sr_uuid): opterr='path is %s' % self.blockdevice) self.isMaster = False - if self.dconf.has_key('SRmaster') and self.dconf['SRmaster'] == 'true': + if 'SRmaster' in self.dconf and self.dconf['SRmaster'] == 'true': self.isMaster = True self.uuid = sr_uuid @@ -88,7 +88,7 @@ def mount(self, mountpoint, blockdevice): 'noatime,data=writeback,nointr,commit=60,coherency=buffered'] try: ret = util.pread(cmd) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('OCFSMount', opterr='Failed to mount FS. Errno is %d' \ % os.strerror(inst.code)) @@ -117,7 +117,7 @@ def detach(self, sr_uuid): cmd = ['umount', self.path ] try: ret = util.pread(cmd) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('OCFSUnMount', \ opterr='Failed to umount FS. Errno is %d' % \ os.strerror(inst.code)) @@ -131,7 +131,7 @@ def create(self, sr_uuid, size): cmd = ['mkfs', '-t', 'ocfs2', '-b', '4K', '-C', '1M', '-N', '16', '-F', self.blockdevice ] try: ret = util.pread(cmd) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('OCFSFilesystem', \ opterr='mkfs failed error %d' % os.strerror(inst.code)) diff --git a/drivers/OCFSoHBASR.py b/drivers/OCFSoHBASR.py index 6716dea8c..dcea555e0 100755 --- a/drivers/OCFSoHBASR.py +++ b/drivers/OCFSoHBASR.py @@ -19,6 +19,7 @@ # based iSCSI # +from __future__ import print_function import SR, VDI, OCFSSR, SRCommand, devscan, HBASR import util import os, sys, re @@ -62,8 +63,8 @@ def load(self, sr_uuid): except: pass - if not self.dconf.has_key('SCSIid') or not self.dconf['SCSIid']: - print >>sys.stderr,self.hbasr.print_devs() + if 'SCSIid' not in self.dconf or not self.dconf['SCSIid']: + print(self.hbasr.print_devs(), file=sys.stderr) raise xs_errors.XenError('ConfigSCSIid') self.SCSIid = self.dconf['SCSIid'] @@ -116,7 +117,7 @@ def scan(self, sr_uuid): super(OCFSoHBASR, self).scan(sr_uuid) def probe(self): - if self.mpath == "true" and self.dconf.has_key('SCSIid'): + if self.mpath == "true" and 'SCSIid' in self.dconf: # When multipathing is enabled, since we don't refcount the # multipath maps, we should not attempt to do the iscsi.attach/ # detach when the map is already present, as this will remove it diff --git a/drivers/OCFSoISCSISR.py b/drivers/OCFSoISCSISR.py index f48495ef4..a9984f70a 100755 --- a/drivers/OCFSoISCSISR.py +++ b/drivers/OCFSoISCSISR.py @@ -18,6 +18,7 @@ # OCFSoISCSISR: OCFS over ISCSI software initiator SR driver # +from __future__ import print_function import SR, VDI, OCFSSR, BaseISCSI, SRCommand, util, scsiutil import statvfs import os, sys, time @@ -74,7 +75,7 @@ def load(self, sr_uuid): # This is a probe call, generate a temp sr_uuid sr_uuid = util.gen_uuid() - if self.original_srcmd.dconf.has_key('target'): + if 'target' in self.original_srcmd.dconf: self.original_srcmd.dconf['targetlist'] = self.original_srcmd.dconf['target'] iscsi = BaseISCSI.BaseISCSISR(self.original_srcmd, sr_uuid) self.iscsiSRs = [] @@ -91,7 +92,7 @@ def load(self, sr_uuid): IQNstring = "" IQNs = [] try: - if self.dconf.has_key('multiSession'): + if 'multiSession' in self.dconf: IQNs = self.dconf['multiSession'].split("|") for IQN in IQNs: if IQN: @@ -143,7 +144,7 @@ def load(self, sr_uuid): util.SMlog("Setting targetlist: %s" % srcmd_copy.dconf['targetlist']) self.iscsiSRs.append(BaseISCSI.BaseISCSISR(srcmd_copy, sr_uuid)) pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref) - if pbd <> None and not self.dconf.has_key('multiSession'): + if pbd != None and 'multiSession' not in self.dconf: dconf = self.session.xenapi.PBD.get_device_config(pbd) dconf['multiSession'] = IQNstring self.session.xenapi.PBD.set_device_config(pbd, dconf) @@ -160,7 +161,7 @@ def load(self, sr_uuid): pass # Apart from the upgrade case, user must specify a SCSIid - if not self.dconf.has_key('SCSIid'): + if 'SCSIid' not in self.dconf: # Dual controller issue self.LUNs = {} # Dict for LUNs from all the iscsi objects for ii in range(0, len(self.iscsiSRs)): @@ -279,7 +280,7 @@ def load(self, sr_uuid): iqn = self.iscsiSRs[kkk].targetIQN key = "%s,%s,%s" % (ipaddr,port,iqn) # The final string must preserve the order without repetition - if not IQNs.has_key(key): + if key not in IQNs: IQNs[key] = "" IQNstring += "%s|" % key util.SMlog("IQNstring is now %s" %IQNstring) @@ -288,7 +289,7 @@ def load(self, sr_uuid): # Updating pbd entry, if any try: pbd = util.find_my_pbd(self.session, self.host_ref, self.sr_ref) - if pbd <> None and self.dconf.has_key('multiSession'): + if pbd != None and 'multiSession' in self.dconf: util.SMlog("Updating multiSession in PBD") dconf = self.session.xenapi.PBD.get_device_config(pbd) dconf['multiSession'] = IQNstring @@ -337,7 +338,7 @@ def print_LUNs_XML(self): textnode = dom.createTextNode(str(aval)) subentry.appendChild(textnode) - print >>sys.stderr,dom.toprettyxml() + print(dom.toprettyxml(), file=sys.stderr) def _getSCSIid_from_LUN(self, sr_uuid): was_attached = True @@ -449,7 +450,7 @@ def create(self, sr_uuid, size): raise xs_errors.XenError('InvalidDev') self._pathrefresh(OCFSoISCSISR) OCFSSR.OCFSSR.create(self, sr_uuid, size) - except Exception, inst: + except Exception as inst: self.iscsi.detach(sr_uuid) raise xs_errors.XenError("SRUnavailable", opterr=inst) self.iscsi.detach(sr_uuid) @@ -465,7 +466,7 @@ def attach(self, sr_uuid): for i in self.iscsiSRs: try: i.attach(sr_uuid) - except SR.SROSError, inst: + except SR.SROSError as inst: # Some iscsi objects can fail login but not all. Storing exception if inst.errno == 141: util.SMlog("Connection failed for target %s, continuing.." %i.target) @@ -481,13 +482,13 @@ def attach(self, sr_uuid): if not i._attach_LUN_bySCSIid(self.SCSIid): raise xs_errors.XenError('InvalidDev') - if self.dconf.has_key('multiSession'): + if 'multiSession' in self.dconf: # Force a manual bus refresh for a in self.iscsi.adapter: scsiutil.rescan([self.iscsi.adapter[a]]) self._pathrefresh(OCFSoISCSISR) OCFSSR.OCFSSR.attach(self, sr_uuid) - except Exception, inst: + except Exception as inst: for i in self.iscsiSRs: i.detach(sr_uuid) raise xs_errors.XenError("SRUnavailable", opterr=inst) @@ -501,7 +502,7 @@ def detach(self, sr_uuid): def probe(self): self.uuid = util.gen_uuid() - if self.mpath == 'true' and self.dconf.has_key('SCSIid'): + if self.mpath == 'true' and 'SCSIid' in self.dconf: # When multipathing is enabled, since we don't refcount the # multipath maps, we should not attempt to do the iscsi.attach/ # detach when the map is already present, as this will remove it @@ -535,7 +536,7 @@ def generate_config(self, sr_uuid, vdi_uuid): self.sr.dconf['multipathing'] = self.sr.mpath self.sr.dconf['multipathhandle'] = self.sr.mpathhandle dict['device_config'] = self.sr.dconf - if dict['device_config'].has_key('chappassword_secret'): + if 'chappassword_secret' in dict['device_config']: s = util.get_secret(self.session, dict['device_config']['chappassword_secret']) del dict['device_config']['chappassword_secret'] dict['device_config']['chappassword'] = s diff --git a/drivers/RawHBASR.py b/drivers/RawHBASR.py index 08c335a35..8fcd98529 100755 --- a/drivers/RawHBASR.py +++ b/drivers/RawHBASR.py @@ -96,7 +96,7 @@ def _loadvdis(self): # The way we create vdi_path and the following check are # not clear at all vdi_path = os.path.join("/dev",key) - if not self.devs.has_key(vdi_path): + if vdi_path not in self.devs: continue scsi_id = scsiutil.getSCSIid(vdi_path) @@ -107,9 +107,9 @@ def _loadvdis(self): # Avoid false positives: this SR can already contain this # SCSIid during scan. scsi_key = "scsi-" + scsi_id - if sm_config.has_key(scsi_key): + if scsi_key in sm_config: # if we know about this scsid we can skip this specific dev - if known_scsid.has_key(scsi_key): + if scsi_key in known_scsid: util.SMlog("This SCSI id (%s) is already added" %scsi_id) continue else: @@ -127,7 +127,7 @@ def _loadvdis(self): # uuid as key. # We have already checked known_scsid, though. This block is # supposed to be always False - if self.vdis.has_key(uuid): + if uuid in self.vdis: util.SMlog("Warning: unexpected code block reached with" " uuid = %s" %scsi_id) continue @@ -142,7 +142,7 @@ def _loadvdis(self): count += 1 # If we know about it no need to add to sm_config - if known_scsid.has_key(scsi_key): + if scsi_key in known_scsid: continue # Prepare multipathing and make the other SRs know this SCSIid diff --git a/drivers/SHMSR.py b/drivers/SHMSR.py index 745803a93..b52b2fb95 100644 --- a/drivers/SHMSR.py +++ b/drivers/SHMSR.py @@ -63,14 +63,14 @@ def content_type(self, sr_uuid): def vdi(self, uuid): """Create a VDI class""" - if self.srcmd.params.has_key('vdi_location'): + if 'vdi_location' in self.srcmd.params: return SHMVDI(self, uuid, self.srcmd.params['vdi_location']) else: return SHMVDI(self, uuid, self.srcmd.params['device_config']['location']) def load(self, sr_uuid): """Initialises the SR""" - if not self.dconf.has_key('location'): + if 'location' not in self.dconf: raise xs_errors.XenError('ConfigLocationMissing') self.sr_vditype = 'file' diff --git a/drivers/SMBSR.py b/drivers/SMBSR.py index 1110dfa62..b2c08c573 100755 --- a/drivers/SMBSR.py +++ b/drivers/SMBSR.py @@ -74,7 +74,7 @@ def load(self, sr_uuid): self.lock = Lock(vhdutil.LOCK_TYPE_SR, self.uuid) self.sr_vditype = SR.DEFAULT_TAP self.driver_config = DRIVER_CONFIG - if not self.dconf.has_key('server'): + if 'server' not in self.dconf: raise xs_errors.XenError('ConfigServerMissing') self.remoteserver = self.dconf['server'] if self.sr_ref and self.session is not None : @@ -105,7 +105,7 @@ def makeMountPoint(self, mountpoint): try: if not util.ioretry(lambda: util.isdir(mountpoint)): util.ioretry(lambda: util.makedirs(mountpoint)) - except util.CommandException, inst: + except util.CommandException as inst: raise SMBException("Failed to make directory: code is %d" % inst.code) return mountpoint @@ -127,7 +127,7 @@ def mount(self, mountpoint=None): mountpoint, "-o", options], new_env=new_env), errlist=[errno.EPIPE, errno.EIO], maxretry=2, nofail=True) - except util.CommandException, inst: + except util.CommandException as inst: raise SMBException("mount failed with return code %d" % inst.code) # Sanity check to ensure that the user has at least RO access to the @@ -163,13 +163,13 @@ def unmount(self, mountpoint, rmmountpoint): """Unmount the remote SMB export at 'mountpoint'""" try: util.pread(["umount", mountpoint]) - except util.CommandException, inst: + except util.CommandException as inst: raise SMBException("umount failed with return code %d" % inst.code) if rmmountpoint: try: os.rmdir(mountpoint) - except OSError, inst: + except OSError as inst: raise SMBException("rmdir failed with error '%s'" % inst.strerror) def __extract_server(self): @@ -191,7 +191,7 @@ def attach(self, sr_uuid): try: self.mount() os.symlink(self.linkpath, self.path) - except SMBException, exc: + except SMBException as exc: raise xs_errors.XenError('SMBMount', opterr=exc.errstr) self.attached = True @@ -202,7 +202,7 @@ def probe(self): sr_list = filter(util.match_uuid, util.listdir(PROBE_MOUNTPOINT)) err = "SMBUnMount" self.unmount(PROBE_MOUNTPOINT, True) - except SMBException, inst: + except SMBException as inst: raise xs_errors.XenError(err, opterr=inst.errstr) except (util.CommandException, xs_errors.XenError): raise @@ -225,7 +225,7 @@ def detach(self, sr_uuid): try: self.unmount(self.mountpoint, True) os.unlink(self.path) - except SMBException, exc: + except SMBException as exc: raise xs_errors.XenError('SMBUnMount', opterr=exc.errstr) self.attached = False @@ -238,7 +238,7 @@ def create(self, sr_uuid, size): try: self.mount() - except SMBException, exc: + except SMBException as exc: try: os.rmdir(self.mountpoint) except: @@ -253,7 +253,7 @@ def create(self, sr_uuid, size): try: util.ioretry(lambda: util.makedirs(self.linkpath)) os.symlink(self.linkpath, self.path) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.EEXIST: try: self.unmount(self.mountpoint, True) @@ -277,7 +277,7 @@ def delete(self, sr_uuid): if util.ioretry(lambda: util.pathexists(self.linkpath)): util.ioretry(lambda: os.rmdir(self.linkpath)) self.unmount(self.mountpoint, True) - except util.CommandException, inst: + except util.CommandException as inst: self.detach(sr_uuid) if inst.code != errno.ENOENT: raise xs_errors.XenError('SMBDelete') diff --git a/drivers/SR.py b/drivers/SR.py index b8dda2661..f12e783f1 100755 --- a/drivers/SR.py +++ b/drivers/SR.py @@ -92,7 +92,7 @@ def __init__(self, srcmd, sr_uuid): try: self.srcmd = srcmd self.dconf = srcmd.dconf - if srcmd.params.has_key('session_ref'): + if 'session_ref' in srcmd.params: self.session_ref = srcmd.params['session_ref'] self.session = XenAPI.xapi_local() self.session._session = self.session_ref @@ -113,14 +113,14 @@ def __init__(self, srcmd, sr_uuid): os.environ['LVM_SYSTEM_DIR'] = MASTER_LVM_CONF if 'device_config' in self.srcmd.params: - if self.srcmd.params['device_config'].has_key('SCSIid'): + if 'SCSIid' in self.srcmd.params['device_config']: dev_path = '/dev/disk/by-scsid/'+self.srcmd.params['device_config']['SCSIid'] os.environ['LVM_DEVICE'] = dev_path util.SMlog('Setting LVM_DEVICE to %s' % dev_path) except TypeError: raise Exception(traceback.format_exc()) - except Exception, e: + except Exception as e: raise e raise xs_errors.XenError('SRBadXML') @@ -214,7 +214,7 @@ def block_setscheduler(self, dev): util.SMlog("Block scheduler: %s (%s) wants %s" % (dev, disk, sched)) util.set_scheduler(realdev[5:], sched) - except Exception, e: + except Exception as e: util.SMlog("Failed to set block scheduler on %s: %s" % (dev, e)) def _addLUNperVDIkey(self): @@ -348,7 +348,7 @@ def load(self, sr_uuid): def vdi(self, uuid): """Return VDI object owned by this repository""" - if not self.vdis.has_key(uuid): + if uuid not in self.vdis: self.vdis[uuid] = VDI.VDI(self, uuid) raise xs_errors.XenError('Unimplemented') return self.vdis[uuid] @@ -453,8 +453,8 @@ def _splitstring(self, str): def _mpathinit(self): self.mpath = "false" try: - if self.dconf.has_key('multipathing') and \ - self.dconf.has_key('multipathhandle'): + if 'multipathing' in self.dconf and \ + 'multipathhandle' in self.dconf: self.mpath = self.dconf['multipathing'] self.mpathhandle = self.dconf['multipathhandle'] else: @@ -510,7 +510,7 @@ def check_dconf(self, key_list, raise_flag=True): Raise: xs_errors.XenError('ConfigParamsMissing') """ - missing_keys = {key for key in key_list if not self.dconf.has_key(key)} + missing_keys = {key for key in key_list if key not in self.dconf} if missing_keys and raise_flag: errstr = 'device-config is missing the following parameters: ' + \ @@ -564,11 +564,11 @@ def __init__(self, sr): # Only consider those whose configuration looks different self.existing = filter(lambda x:not(self.get_sm_vdi(x).in_sync_with_xenapi_record(self.get_xenapi_vdi(x))), existing) - if len(self.new) <> 0: + if len(self.new) != 0: util.SMlog("new VDIs on disk: " + repr(self.new)) - if len(self.gone) <> 0: + if len(self.gone) != 0: util.SMlog("VDIs missing from disk: " + repr(self.gone)) - if len(self.existing) <> 0: + if len(self.existing) != 0: util.SMlog("VDIs changed on disk: " + repr(self.existing)) def get_sm_vdi(self, location): @@ -594,7 +594,7 @@ def synchronise_gone(self): util.SMlog("Forgetting VDI with location=%s uuid=%s" % (util.to_plain_string(vdi['location']), vdi['uuid'])) try: self.sr.forget_vdi(vdi['uuid']) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if util.isInvalidVDI(e): util.SMlog("VDI %s not found, ignoring exception" \ % vdi['uuid']) diff --git a/drivers/SRCommand.py b/drivers/SRCommand.py index a7e49c630..e5edb2672 100755 --- a/drivers/SRCommand.py +++ b/drivers/SRCommand.py @@ -18,6 +18,7 @@ # SRCommand: parse SR command-line objects # +from __future__ import print_function import XenAPI import sys import xs_errors @@ -69,7 +70,7 @@ def __init__(self, driver_info): self.driver_info = driver_info def parse(self): - if len(sys.argv) <> 2: + if len(sys.argv) != 2: util.SMlog("Failed to parse commandline; wrong number of arguments; argv = %s" % (repr(sys.argv))) raise xs_errors.XenError('BadRequest') @@ -89,26 +90,26 @@ def parse(self): # params is a dictionary self.dconf = params['device_config'] - if params.has_key('sr_uuid'): + if 'sr_uuid' in params: self.sr_uuid = params['sr_uuid'] - if params.has_key('vdi_uuid'): + if 'vdi_uuid' in params: self.vdi_uuid = params['vdi_uuid'] elif self.cmd == "vdi_create": self.vdi_uuid = util.gen_uuid () - except Exception, e: + except Exception as e: util.SMlog("Failed to parse commandline; exception = %s argv = %s" % (str(e), repr(sys.argv))) raise xs_errors.XenError('BadRequest') def run_statics(self): if self.params['command'] == 'sr_get_driver_info': - print util.sr_get_driver_info(self.driver_info) + print(util.sr_get_driver_info(self.driver_info)) sys.exit(0) def run(self, sr): try: return self._run_locked(sr) - except (util.CommandException, util.SMException, XenAPI.Failure), e: + except (util.CommandException, util.SMException, XenAPI.Failure) as e: util.logException(self.cmd) msg = str(e) if isinstance(e, util.CommandException): @@ -119,12 +120,12 @@ def run(self, sr): excType = "SMGeneral" raise xs_errors.XenError(excType, opterr=msg) - except blktap2.TapdiskFailed, e: + except blktap2.TapdiskFailed as e: util.logException('tapdisk failed exception: %s' % e) raise xs_errors.XenError('TapdiskFailed', os.strerror(e.get_error().get_error_code())) - except blktap2.TapdiskExists, e: + except blktap2.TapdiskExists as e: util.logException('tapdisk exists exception: %s' % e) raise xs_errors.XenError('TapdiskAlreadyRunning', e.__str__()) @@ -157,14 +158,14 @@ def _run_locked(self, sr): acquired = False try: rv = self._run(sr, target) - except Exception, e: + except Exception as e: raise finally: if acquired: sr.lock.release() try: sr.cleanup() - except Exception, e1: + except Exception as e1: msg = 'failed to clean up SR: %s' % e1 if not e: util.SMlog(msg) @@ -378,9 +379,9 @@ def run(driver, driver_info): ret = cmd.run(sr) if ret == None: - print util.return_nil () + print(util.return_nil ()) else: - print ret + print(ret) except (Exception, SR.SRException) as e: try: @@ -394,8 +395,8 @@ def run(driver, driver_info): # If generic python Exception, print a generic xmlrpclib # dump and pass to XAPI. if isinstance(e, SR.SRException): - print e.toxml() + print(e.toxml()) else: - print xmlrpclib.dumps(xmlrpclib.Fault(1200, str(e)), "", True) + print(xmlrpclib.dumps(xmlrpclib.Fault(1200, str(e)), "", True)) sys.exit(0) diff --git a/drivers/VDI.py b/drivers/VDI.py index fed8baabf..94b7e326f 100755 --- a/drivers/VDI.py +++ b/drivers/VDI.py @@ -79,7 +79,7 @@ def __init__(self, sr, uuid): self.sr = sr # Don't set either the UUID or location to None- no good can # ever come of this. - if uuid <> None: + if uuid != None: self.uuid = uuid self.location = uuid self.path = None @@ -406,7 +406,7 @@ def snapshot(self, sr_uuid, vdi_uuid): def activate(self, sr_uuid, vdi_uuid): """Activate VDI - called pre tapdisk open""" if self._get_blocktracking_status(): - if self.sr.srcmd.params.has_key('args'): + if 'args' in self.sr.srcmd.params: read_write = self.sr.srcmd.params['args'][0] if read_write == "false": # Disk is being attached in RO mode, @@ -474,7 +474,7 @@ def load(self, vdi_uuid): def _db_introduce(self): uuid = util.default(self, "uuid", lambda: util.gen_uuid()) sm_config = util.default(self, "sm_config", lambda: {}) - if self.sr.srcmd.params.has_key("vdi_sm_config"): + if "vdi_sm_config" in self.sr.srcmd.params: for key in SM_CONFIG_PASS_THROUGH_FIELDS: val = self.sr.srcmd.params["vdi_sm_config"].get(key) if val: @@ -499,7 +499,7 @@ def _override_sm_config(self, sm_config): util.SMlog("_override_sm_config: %s: %s -> %s" % \ (key, sm_config.get(key), val)) sm_config[key] = val - elif sm_config.has_key(key): + elif key in sm_config: util.SMlog("_override_sm_config: del %s" % key) del sm_config[key] @@ -539,24 +539,24 @@ def _db_update(self): def in_sync_with_xenapi_record(self, x): """Returns true if this VDI is in sync with the supplied XenAPI record""" - if self.location <> util.to_plain_string(x['location']): + if self.location != util.to_plain_string(x['location']): util.SMlog("location %s <> %s" % (self.location, x['location'])) return False - if self.read_only <> x['read_only']: + if self.read_only != x['read_only']: util.SMlog("read_only %s <> %s" % (self.read_only, x['read_only'])) return False - if str(self.size) <> x['virtual_size']: + if str(self.size) != x['virtual_size']: util.SMlog("virtual_size %s <> %s" % (self.size, x['virtual_size'])) return False - if str(self.utilisation) <> x['physical_utilisation']: + if str(self.utilisation) != x['physical_utilisation']: util.SMlog("utilisation %s <> %s" % (self.utilisation, x['physical_utilisation'])) return False sm_config = util.default(self, "sm_config", lambda: {}) - if set(sm_config.keys()) <> set(x['sm_config'].keys()): + if set(sm_config.keys()) != set(x['sm_config'].keys()): util.SMlog("sm_config %s <> %s" % (repr(sm_config), repr(x['sm_config']))) return False for k in sm_config.keys(): - if sm_config[k] <> x['sm_config'][k]: + if sm_config[k] != x['sm_config'][k]: util.SMlog("sm_config %s <> %s" % (repr(sm_config), repr(x['sm_config']))) return False if self.cbt_enabled != x['cbt_enabled']: diff --git a/drivers/blktap2.py b/drivers/blktap2.py index 16a05c5e3..a31e63ce5 100755 --- a/drivers/blktap2.py +++ b/drivers/blktap2.py @@ -19,6 +19,7 @@ # +from __future__ import print_function import os import sys import re @@ -29,6 +30,7 @@ import xmlrpclib import httplib import errno +import signal import subprocess import syslog as _syslog import glob @@ -82,7 +84,7 @@ def wrapper(self, *args): try: try: ret = op(self, *args) - except (util.CommandException, util.SMException, XenAPI.Failure), e: + except (util.CommandException, util.SMException, XenAPI.Failure) as e: util.logException("BLKTAP2:%s" % op) msg = str(e) if isinstance(e, util.CommandException): @@ -118,7 +120,7 @@ def loop(*__t, **__d): try: return f(*__t, **__d) - except self.TransientFailure, e: + except self.TransientFailure as e: e = e.exception if attempt >= self.limit: raise e @@ -159,7 +161,7 @@ def __str__(self): # Trying to get a non-existent attribute throws an AttributeError # exception def __getattr__(self, key): - if self.info.has_key(key): return self.info[key] + if key in self.info: return self.info[key] return object.__getattribute__(self, key) @property @@ -174,7 +176,7 @@ def has_signal(self): # was not supplied at object-construction time, zero is returned. def get_error_code(self): key = 'status' - if self.info.has_key(key): + if key in self.info: return self.info[key] else: return 0 @@ -212,7 +214,7 @@ def _call(cls, args, quiet = False, input = None): if input: p.stdin.write(input) p.stdin.close() - except OSError, e: + except OSError as e: raise cls.CommandFailure(cmd, errno=e.errno) return cls(cmd, p) @@ -275,7 +277,7 @@ def __list(cls, minor = None, pid = None, _type = None, path = None): if line == "blktap kernel module not installed\n": # This isn't pretty but (a) neither is confusing stdout/stderr # and at least causes the error to describe the fix - raise Exception, "blktap kernel module not installed: try 'modprobe blktap'" + raise Exception("blktap kernel module not installed: try 'modprobe blktap'") row = {} for field in line.rstrip().split(' ', 3): @@ -308,7 +310,7 @@ def list(cls, **args): try: return list(cls.__list(**args)) - except cls.CommandFailure, e: + except cls.CommandFailure as e: transient = [ errno.EPROTO, errno.ENOENT ] if e.has_status and e.status in transient: raise RetryLoop.TransientFailure(e) @@ -413,6 +415,12 @@ def unpause(cls, pid, minor, _type = None, _file = None, mirror = None, args.extend(["-c", cbtlog]) cls._pread(args) + @classmethod + def shutdown(cls, pid): + # TODO: This should be a real tap-ctl command + os.kill(pid, signal.SIGTERM) + os.waitpid(pid, 0) + @classmethod def stats(cls, pid, minor): args = [ "stats", "-p", pid, "-m", minor ] @@ -477,7 +485,7 @@ def __init__(self, tapdisk): def __str__(self): return str(self.tapdisk) -def mkdirs(path, mode=0777): +def mkdirs(path, mode=0o777): if not os.path.exists(path): parent, subdir = os.path.split(path) assert parent != path @@ -486,7 +494,7 @@ def mkdirs(path, mode=0777): mkdirs(parent, mode) if subdir: os.mkdir(path, mode) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise @@ -520,7 +528,7 @@ def __str__(self): def _open(self, mode='r'): try: return file(self.path, mode) - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: raise self.NoSuchAttribute(self) raise @@ -796,16 +804,10 @@ def launch_on_tap(cls, blktap, path, _type, options): raise except: - exc_info = sys.exc_info() - # FIXME: Should be tap-ctl shutdown. - try: - import signal - os.kill(pid, signal.SIGTERM) - os.waitpid(pid, 0) - finally: - raise exc_info[0], exc_info[1], exc_info[2] + TapCtl.shutdown(pid) + raise - except TapCtl.CommandFailure, ctl: + except TapCtl.CommandFailure as ctl: util.logException(ctl) if ('/dev/xapi/cd/' in path and 'status' in ctl.info and @@ -921,8 +923,7 @@ def _parse_minor(devpath): pattern = re.compile(regex) groups = pattern.search(devpath) if not groups: - raise Exception, \ - "malformed tap device: '%s' (%s) " % (devpath, regex) + raise Exception("malformed tap device: '%s' (%s) " % (devpath, regex)) minor = groups.group(2) return int(minor) @@ -1167,7 +1168,7 @@ def mklink(self, target): mkdirs(os.path.dirname(path)) try: self._mklink(target) - except OSError, e: + except OSError as e: # We do unlink during teardown, but have to stay # idempotent. However, a *wrong* target should never # be seen. @@ -1177,7 +1178,7 @@ def mklink(self, target): def unlink(self): try: os.unlink(self.path()) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise def __str__(self): @@ -1307,7 +1308,7 @@ def _tap_deactivate(minor): try: tapdisk = Tapdisk.from_minor(minor) - except TapdiskNotRunning, e: + except TapdiskNotRunning as e: util.SMlog("tap.deactivate: Warning, %s" % e) # NB. Should not be here unless the agent refcount # broke. Also, a clean shutdown should not have leaked @@ -1397,7 +1398,7 @@ def call_pluginhandler(cls, session, host_ref, sr_uuid, vdi_uuid, action, host_ref, PLUGIN_TAP_PAUSE, action, args) return ret == "True" - except Exception, e: + except Exception as e: util.logException("BLKTAP2:call_pluginhandler %s" % e) return False @@ -1418,15 +1419,15 @@ def _add_tag(self, vdi_uuid, writable): term_output=False, writable=writable): raise util.SMException("VDI %s not detached cleanly" % vdi_uuid) sm_config = self._session.xenapi.VDI.get_sm_config(vdi_ref) - if sm_config.has_key('paused'): + if 'paused' in sm_config: util.SMlog("Paused or host_ref key found [%s]" % sm_config) return False host_key = "host_%s" % host_ref - assert not sm_config.has_key(host_key) + assert host_key not in sm_config self._session.xenapi.VDI.add_to_sm_config(vdi_ref, host_key, attach_mode) sm_config = self._session.xenapi.VDI.get_sm_config(vdi_ref) - if sm_config.has_key('paused'): + if 'paused' in sm_config: util.SMlog("Found paused key, aborting") self._session.xenapi.VDI.remove_from_sm_config(vdi_ref, host_key) return False @@ -1436,7 +1437,7 @@ def _add_tag(self, vdi_uuid, writable): def _check_tag(self, vdi_uuid): vdi_ref = self._session.xenapi.VDI.get_by_uuid(vdi_uuid) sm_config = self._session.xenapi.VDI.get_sm_config(vdi_ref) - if sm_config.has_key('paused'): + if 'paused' in sm_config: util.SMlog("Paused key found [%s]" % sm_config) return False return True @@ -1446,7 +1447,7 @@ def _remove_tag(self, vdi_uuid): host_ref = self._session.xenapi.host.get_by_uuid(util.get_this_host()) sm_config = self._session.xenapi.VDI.get_sm_config(vdi_ref) host_key = "host_%s" % host_ref - if sm_config.has_key(host_key): + if host_key in sm_config: self._session.xenapi.VDI.remove_from_sm_config(vdi_ref, host_key) util.SMlog("Removed host key %s for %s" % (host_key, vdi_uuid)) else: @@ -1624,14 +1625,14 @@ def _activate_locked(self, sr_uuid, vdi_uuid, options): try: self._remove_tag(vdi_uuid) break - except xmlrpclib.ProtocolError, e: + except xmlrpclib.ProtocolError as e: # If there's a connection error, keep trying forever. if e.errcode == httplib.INTERNAL_SERVER_ERROR: continue else: util.SMlog('failed to remove tag: %s' % e) break - except Exception, e: + except Exception as e: util.SMlog('failed to remove tag: %s' % e) break raise @@ -1676,7 +1677,7 @@ def deactivate(self, sr_uuid, vdi_uuid, caching_params): try: if self._deactivate_locked(sr_uuid, vdi_uuid, caching_params): return - except util.SRBusyException, e: + except util.SRBusyException as e: util.SMlog("SR locked, retrying") time.sleep(1) raise util.SMException("VDI %s locked" % vdi_uuid) @@ -1876,7 +1877,7 @@ def _setup_cache(self, session, sr_uuid, vdi_uuid, local_sr_uuid, else: try: vhdutil.snapshot(read_cache_path, shared_target.path, False) - except util.CommandException, e: + except util.CommandException as e: util.SMlog("Error creating parent cache: %s" % e) self.alert_no_cache(session, vdi_uuid, local_sr_uuid, e.code) return None @@ -1892,7 +1893,7 @@ def _setup_cache(self, session, sr_uuid, vdi_uuid, local_sr_uuid, try: vhdutil.snapshot(local_leaf_path, read_cache_path, False, msize = leaf_size / 1024 / 1024, checkEmpty = False) - except util.CommandException, e: + except util.CommandException as e: util.SMlog("Error creating leaf cache: %s" % e) self.alert_no_cache(session, vdi_uuid, local_sr_uuid, e.code) return None @@ -2051,7 +2052,7 @@ def __str__(self): def getenv(cls, key): try: return os.environ[key] - except KeyError, e: + except KeyError as e: raise cls.KeyError(e.args[0]) def get_action(self): @@ -2221,7 +2222,7 @@ def _xs_rm_path(self, path): def read(self, key): return self._xs_read_path(self.xs_path(key)) - def has_key(self, key): + def has_xs_key(self, key): return self.read(key) is not None def write(self, key, val): @@ -2231,7 +2232,7 @@ def rm(self, key): self._xs_rm_path(self.xs_path(key)) def exists(self): - return self.has_key(None) + return self.has_xs_key(None) def begin(self): assert(self._xbt == XenbusDevice.XBT_NIL) @@ -2250,7 +2251,7 @@ def abort(self): def create_physical_device(self): """The standard protocol is: toolstack writes 'params', linux hotplug script translates this into physical-device=%x:%x""" - if self.has_key("physical-device"): + if self.has_xs_key("physical-device"): return try: params = self.read("params") @@ -2351,7 +2352,7 @@ def from_xbdev(cls, xbdev): major, minor = phy.split(':') major = int(major, 0x10) minor = int(minor, 0x10) - except Exception, e: + except Exception as e: raise xbdev.PhysicalDeviceError(xbdev, phy) return cls(major, minor) @@ -2404,16 +2405,16 @@ def get_vdi_uuid(self): return self._vdi_uuid def pause_requested(self): - return self.has_key("pause") + return self.has_xs_key("pause") def shutdown_requested(self): - return self.has_key("shutdown-request") + return self.has_xs_key("shutdown-request") def shutdown_done(self): - return self.has_key("shutdown-done") + return self.has_xs_key("shutdown-done") def running(self): - return self.has_key('queue-0/kthread-pid') + return self.has_xs_key('queue-0/kthread-pid') @classmethod def find_by_physical_device(cls, phy): @@ -2451,7 +2452,7 @@ def is_bare_hvm(self): try: self.get_physical_device() - except self.PhysicalDeviceError, e: + except self.PhysicalDeviceError as e: vdi_type = self.read("type") self.info("HVM VDI: type=%s" % vdi_type) @@ -2539,7 +2540,7 @@ def __add(self): def add(self): try: self.__add() - except Attribute.NoSuchAttribute, e: + except Attribute.NoSuchAttribute as e: # # FIXME: KOBJ_ADD is racing backend.probe, which # registers device attributes. So poll a little. @@ -2697,17 +2698,17 @@ def _signal_xapi(self): handled = 0 if pausing and not running: - if not vbd.has_key('pause-done'): + if 'pause-done' not in vbd: vbd.write('pause-done', '') handled += 1 if not pausing: - if vbd.has_key('pause-done'): + if 'pause-done' in vbd: vbd.rm('pause-done') handled += 1 if closing and not running: - if not vbd.has_key('shutdown-done'): + if 'shutdown-done' not in vbd: vbd.write('shutdown-done', '') handled += 1 @@ -2729,13 +2730,10 @@ def _signal_xapi(self): # def usage(stream): - print >>stream, \ - "usage: %s tap.{list|major}" % prog - print >>stream, \ - " %s tap.{launch|find|get|pause|" % prog + \ - "unpause|shutdown|stats} {[:]} | [minor=] | .. }" - print >>stream, \ - " %s vbd.uevent" % prog + print("usage: %s tap.{list|major}" % prog, file=stream) + print(" %s tap.{launch|find|get|pause|" % prog + \ + "unpause|shutdown|stats} {[:]} | [minor=] | .. }", file=stream) + print(" %s vbd.uevent" % prog, file=stream) try: cmd = sys.argv[1] @@ -2755,12 +2753,12 @@ def usage(stream): if cmd == 'tap.major': - print "%d" % Tapdisk.major() + print("%d" % Tapdisk.major()) elif cmd == 'tap.launch': tapdisk = Tapdisk.launch_from_arg(sys.argv[2]) - print >> sys.stderr, "Launched %s" % tapdisk + print("Launched %s" % tapdisk, file=sys.stderr) elif _class == 'tap': @@ -2793,20 +2791,20 @@ def usage(stream): for tapdisk in Tapdisk.list(**attrs): blktap = tapdisk.get_blktap() - print tapdisk, - print "%s: task=%s pool=%s" % \ + print(tapdisk, end=' ') + print("%s: task=%s pool=%s" % \ (blktap, blktap.get_task_pid(), - blktap.get_pool_name()) + blktap.get_pool_name())) elif cmd == 'tap.vbds': # Find all Blkback instances for a given tapdisk for tapdisk in Tapdisk.list(**attrs): - print "%s:" % tapdisk, + print("%s:" % tapdisk, end=' ') for vbd in Blkback.find_by_tap(tapdisk): - print vbd, - print + print(vbd, end=' ') + print() else: @@ -2823,23 +2821,23 @@ def usage(stream): if cmd == 'tap.shutdown': # Shutdown a running tapdisk, or raise tapdisk.shutdown() - print >> sys.stderr, "Shut down %s" % tapdisk + print("Shut down %s" % tapdisk, file=sys.stderr) elif cmd == 'tap.pause': # Pause an unpaused tapdisk, or raise tapdisk.pause() - print >> sys.stderr, "Paused %s" % tapdisk + print("Paused %s" % tapdisk, file=sys.stderr) elif cmd == 'tap.unpause': # Unpause a paused tapdisk, or raise tapdisk.unpause() - print >> sys.stderr, "Unpaused %s" % tapdisk + print("Unpaused %s" % tapdisk, file=sys.stderr) elif cmd == 'tap.stats': # Gather tapdisk status stats = tapdisk.stats() - print "%s:" % tapdisk - print json.dumps(stats, indent=True) + print("%s:" % tapdisk) + print(json.dumps(stats, indent=True)) else: usage(sys.stderr) @@ -2852,7 +2850,7 @@ def usage(stream): if not sys.stdin.isatty(): try: hnd.run() - except Exception, e: + except Exception as e: hnd.error("Unhandled Exception: %s" % e) import traceback @@ -2867,9 +2865,9 @@ def usage(stream): elif cmd == 'vbd.list': for vbd in Blkback.find(): - print vbd, \ + print(vbd, \ "physical-device=%s" % vbd.get_physical_device(), \ - "pause=%s" % vbd.pause_requested() + "pause=%s" % vbd.pause_requested()) else: usage(sys.stderr) diff --git a/drivers/cleanup.py b/drivers/cleanup.py index 9d863f28a..6a7a1433d 100755 --- a/drivers/cleanup.py +++ b/drivers/cleanup.py @@ -18,6 +18,7 @@ # Script to coalesce and garbage collect VHD-based SR's in the background # +from __future__ import print_function import os import os.path import sys @@ -48,6 +49,7 @@ from ipc import IPCFlag from lvmanager import LVActivator from srmetadata import LVMMetadataHandler +from functools import reduce # Disable automatic leaf-coalescing. Online leaf-coalesce is currently not # possible due to lvhd_stop_using_() not working correctly. However, we leave @@ -192,7 +194,7 @@ def runAbortable(func, ret, ns, abortTest, pollInterval, timeOut): resultFlag.set("success") else: resultFlag.set("failure") - except Exception, e: + except Exception as e: Util.log("Child process failed with : (%s)" % e) resultFlag.set("failure") Util.logException("This exception has occured") @@ -553,7 +555,7 @@ def _report_tapdisk_unpause_error(self): "VMs using this tapdisk have lost access " \ "to the corresponding disk(s)" % self.uuid xapi.message.create(msg_name, "4", "SR", self.sr.uuid, msg_body) - except Exception, e: + except Exception as e: util.SMlog("failed to generate message: %s" % e) def unpause(self): @@ -571,7 +573,7 @@ def refresh(self, ignoreNonexistent = True): self.sr.uuid, self.uuid): self._report_tapdisk_unpause_error() raise util.SMException("Failed to refresh %s" % self) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if util.isInvalidVDI(e) and ignoreNonexistent: Util.log("VDI %s not found, ignoring" % self) return @@ -824,14 +826,14 @@ def _doCoalesceVHD(vdi): vhdutil.coalesce(vdi.path) endTime = time.time() vdi.sr.recordStorageSpeed(startTime, endTime, vhdSize) - except util.CommandException, ce: + except util.CommandException as ce: # We use try/except for the following piece of code because it runs # in a separate process context and errors will not be caught and # reported by anyone. try: # Report coalesce errors back to user via XC VDI._reportCoalesceError(vdi, ce) - except Exception, e: + except Exception as e: util.SMlog('failed to create XenCenter message: %s' % e) raise ce except: @@ -855,7 +857,7 @@ def _coalesceVHD(self, timeOut): util.SMlog('Coalesce failed on %s, attempting repair on ' \ 'parent %s' % (self.uuid, parent)) vhdutil.repair(parent) - except Exception, e: + except Exception as e: util.SMlog('(error ignored) Failed to repair parent %s ' \ 'after failed coalesce on %s, err: %s' % (parent, self.path, e)) @@ -1621,7 +1623,7 @@ def coalesce(self, vdi, dryRun): try: self._coalesce(vdi) - except util.SMException, e: + except util.SMException as e: if isinstance(e, AbortException): self.cleanup() raise @@ -1649,7 +1651,7 @@ def coalesceLeaf(self, vdi, dryRun): except AbortException: self.cleanup() raise - except (util.SMException, XenAPI.Failure), e: + except (util.SMException, XenAPI.Failure) as e: self._failedCoalesceTargets.append(vdi) Util.logException("leaf-coalesce") Util.log("Leaf-coalesce failed on %s, skipping" % vdi) @@ -2003,7 +2005,7 @@ def _snapshotCoalesce(self, vdi): try: ret = self.xapi.singleSnapshotVDI(vdi) Util.log("Single-snapshot returned: %s" % ret) - except XenAPI.Failure, e: + except XenAPI.Failure as e: if util.isInvalidVDI(e): Util.log("The VDI appears to have been concurrently deleted") return False @@ -2948,7 +2950,7 @@ def usage(): -v --vdi_uuid VDI UUID """ #-d --dry-run don't actually perform any SR-modifying operations - print output + print(output) Util.log("(Invalid usage)") sys.exit(1) @@ -3076,18 +3078,18 @@ def debug(sr_uuid, cmd, vdi_uuid): Util.log("Debug command: %s" % cmd) sr = SR.getInstance(sr_uuid, None) if not isinstance(sr, LVHDSR): - print "Error: not an LVHD SR" + print("Error: not an LVHD SR") return sr.scanLocked() vdi = sr.getVDI(vdi_uuid) if not vdi: - print "Error: VDI %s not found" + print("Error: VDI %s not found") return - print "Running %s on SR %s" % (cmd, sr) - print "VDI before: %s" % vdi + print("Running %s on SR %s" % (cmd, sr)) + print("VDI before: %s" % vdi) if cmd == "activate": vdi._activate() - print "VDI file: %s" % vdi.path + print("VDI file: %s" % vdi.path) if cmd == "deactivate": ns = lvhdutil.NS_PREFIX_LVM + sr.uuid sr.lvmCache.deactivate(ns, vdi.uuid, vdi.fileName, False) @@ -3098,14 +3100,14 @@ def debug(sr_uuid, cmd, vdi_uuid): vdi.deflate() sr.cleanup() sr.scanLocked() - print "VDI after: %s" % vdi + print("VDI after: %s" % vdi) def abort_optional_reenable(uuid): - print "Disabling GC/coalesce for %s" % uuid + print("Disabling GC/coalesce for %s" % uuid) ret = _abort(uuid) raw_input("Press enter to re-enable...") - print "GC/coalesce re-enabled" + print("GC/coalesce re-enabled") lockRunning.release() if ret: lockActive.release() @@ -3166,7 +3168,7 @@ def main(): usage() if action != "query" and action != "debug": - print "All output goes to log" + print("All output goes to log") if action == "gc": gc(None, uuid, background, dryRun) @@ -3177,7 +3179,7 @@ def main(): elif action == "abort": abort(uuid) elif action == "query": - print "Currently running: %s" % get_state(uuid) + print("Currently running: %s" % get_state(uuid)) elif action == "disable": abort_optional_reenable(uuid) elif action == "debug": diff --git a/drivers/devscan.py b/drivers/devscan.py index f597bb33e..e41dcff14 100644 --- a/drivers/devscan.py +++ b/drivers/devscan.py @@ -144,7 +144,7 @@ def adapters(filterstr="any"): if path.startswith(SYSFS_PATH2): os.path.join(path,"device","block:*") dev = _extract_dev_name(os.path.join(path, 'device')) - if devs.has_key(dev): + if dev in devs: continue hbtl = os.path.basename(path) (h,b,t,l) = hbtl.split(':') @@ -354,7 +354,7 @@ def scan(srobj): elif util.test_SCSIid(srobj.session, None, obj.SCSIid): util.SMlog("SCSIid in use, ignoring (%s)" % obj.SCSIid) continue - elif not devs.has_key(realpath): + elif realpath not in devs: continue ids = devs[realpath] @@ -363,15 +363,15 @@ def scan(srobj): obj.id = ids[3] obj.lun = ids[4] obj.hba = hba['procname'] - if hba.has_key('eth') and hba['eth']: + if 'eth' in hba and hba['eth']: obj.eth = hba['eth'] obj.numpaths = 1 - if vdis.has_key(obj.SCSIid): + if obj.SCSIid in vdis: vdis[obj.SCSIid].numpaths += 1 vdis[obj.SCSIid].path += " [%s]" % key elif obj.hba == 'mpp': mppdict = _genMPPHBA(obj.adapter) - if mppdict.has_key(key): + if key in mppdict: item = mppdict[key] adapters = '' for i in item: diff --git a/drivers/fjournaler.py b/drivers/fjournaler.py index 7d06856d0..ec87b1a82 100644 --- a/drivers/fjournaler.py +++ b/drivers/fjournaler.py @@ -17,6 +17,7 @@ # # File-based journaling +from __future__ import print_function import os import errno @@ -61,7 +62,7 @@ def get(self, type, id): return None try: f = open(path, "r") - except IOError, e: + except IOError as e: if e.errno == errno.ENOENT: # the file can disappear any time, since there is no locking return None @@ -100,51 +101,51 @@ def _getPath(self, type, id): def _runTests(): """Unit testing""" dir = "/tmp" - print "Running unit tests..." + print("Running unit tests...") j = Journaler(dir) if j.get("clone", "1"): - print "get non-existing failed" + print("get non-existing failed") return 1 j.create("clone", "1", "a") val = j.get("clone", "1") if val != "a": - print "create-get failed" + print("create-get failed") return 1 j.remove("clone", "1") if j.get("clone", "1"): - print "remove failed" + print("remove failed") return 1 j.create("modify", "X", "831_3") j.create("modify", "Z", "831_4") j.create("modify", "Y", "53_0") val = j.get("modify", "X") if val != "831_3": - print "create underscore_val failed" + print("create underscore_val failed") return 1 val = j.get("modify", "Y") if val != "53_0": - print "create multiple id's failed" + print("create multiple id's failed") return 1 entries = j.getAll("modify") if not entries.get("X") or not entries.get("Y") or \ entries["X"] != "831_3" or entries["Y"] != "53_0": - print "getAll failed: %s" % entries + print("getAll failed: %s" % entries) return 1 j.remove("modify", "X") val = j.getAll("modify") if val.get("X") or not val.get("Y") or val["Y"] != "53_0": - print "remove(X) failed" + print("remove(X) failed") return 1 j.remove("modify", "Y") j.remove("modify", "Z") if j.get("modify", "Y"): - print "remove(Y) failed" + print("remove(Y) failed") return 1 if j.get("modify", "Z"): - print "remove(Z) failed" + print("remove(Z) failed") return 1 - print "All tests passed" + print("All tests passed") return 0 if __name__ == '__main__': diff --git a/drivers/flock.py b/drivers/flock.py index 115f352f3..a659114a9 100644 --- a/drivers/flock.py +++ b/drivers/flock.py @@ -97,7 +97,7 @@ def trylock(self): if self._held: return False try: Flock(self.LOCK_TYPE).fcntl(self.fd, fcntl.F_SETLK) - except IOError, e: + except IOError as e: if e.errno in [errno.EACCES, errno.EAGAIN]: return False raise diff --git a/drivers/ipc.py b/drivers/ipc.py index 0deb2bdee..e2dede017 100644 --- a/drivers/ipc.py +++ b/drivers/ipc.py @@ -16,6 +16,7 @@ # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA """Communication for processes""" +from __future__ import print_function import os import util @@ -61,13 +62,13 @@ def set(self, name, soft=False): f.close() util.SMlog("IPCFlag: set %s:%s" % (self.ns, name)) return True - except OSError, e: + except OSError as e: if e.errno == errno.EEXIST and soft: return False else: raise IPCFlagException("failed to create %s: %s" \ % (flagFile, e)) - except IOError, e: + except IOError as e: raise IPCFlagException("failed to create %s: %s" % (flagFile, e)) def test(self, name): @@ -110,7 +111,7 @@ def _runTests(): assert not flag.test("X") assert not flag.test("Y") assert not flag.test("Z") - print "All tests passed" + print("All tests passed") if __name__ == '__main__': _runTests() diff --git a/drivers/iscsilib.py b/drivers/iscsilib.py index 75cb4934b..026007a55 100644 --- a/drivers/iscsilib.py +++ b/drivers/iscsilib.py @@ -55,7 +55,7 @@ def doexec_locked(cmd): _lock.acquire() #util.SMlog("%s" % (cmd)) (rc,stdout,stderr) = util.doexec(cmd) - if _lock <> None and _lock.held(): + if _lock != None and _lock.held(): _lock.release() return (rc, stdout, stderr) @@ -289,7 +289,7 @@ def get_current_initiator_name(): f.close() return currentIQN f.close() - except IOError, e: + except IOError as e: return None return None @@ -307,7 +307,7 @@ def set_current_initiator_name(localIQN): f.write('InitiatorName=%s\n' % localIQN) f.write('InitiatorAlias=%s\n' % alias) f.close() - except IOError, e: + except IOError as e: raise xs_errors.XenError('ISCSIInitiator', \ opterr='Could not set initator name') @@ -355,7 +355,7 @@ def get_luns(targetIQN, portal): lun=file.replace("LUN","") luns.append(lun) return luns - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('ISCSIDevice', opterr='Failed to find any LUNs') def is_iscsi_daemon_running(): @@ -466,7 +466,7 @@ def _checkTGT(tgtIQN, tgt=''): (stdout,stderr) = exn_on_failure(cmd, failuremessage) # Recent versions of iscsiadm return error it this list is empty. # Quick and dirty handling - except Exception, e: + except Exception as e: util.SMlog("%s failed with %s" %(cmd, e.args)) stdout = "" for line in stdout.split('\n'): @@ -495,7 +495,7 @@ def _checkAnyTGT(): (stdout,stderr) = exn_on_failure(cmd, failuremessage) # Recent versions of iscsiadm return error it this list is empty. # Quick and dirty handling - except Exception, e: + except Exception as e: util.SMlog("%s failed with %s" %(cmd, e.args)) stdout = "" for e in filter(match_session, stdout.split('\n')): diff --git a/drivers/journaler.py b/drivers/journaler.py index 9d40edf35..e6d98ae24 100644 --- a/drivers/journaler.py +++ b/drivers/journaler.py @@ -17,6 +17,7 @@ # # LVM-based journaling +from __future__ import print_function import util from srmetadata import open_file, close, get_min_blk_size_wrapper, \ file_read_wrapper, file_write_wrapper @@ -69,13 +70,13 @@ def create(self, type, id, val): min_block_size = get_min_blk_size_wrapper(fd) data = "%d %s" % (len(val), val) file_write_wrapper(fd, 0, min_block_size, data, len(data)) - except Exception, e: + except Exception as e: raise finally: try: close(fd) self.lvmCache.deactivateNoRefcount(lvName) - except Exception, e2: + except Exception as e2: msg = 'failed to close/deactivate %s: %s' \ % (lvName, e2) if not e: @@ -88,7 +89,7 @@ def create(self, type, id, val): util.logException("journaler.create") try: self.lvmCache.remove(lvName) - except Exception, e: + except Exception as e: util.SMlog('WARNING: failed to clean up failed journal ' \ ' creation: %s (error ignored)' % e) raise JournalerException("Failed to write to journal %s" \ @@ -179,57 +180,57 @@ def _getLVMapperName(self, lvName): def _runTests(vgName): """Unit testing""" - print "Running unit tests..." + print("Running unit tests...") if not vgName: - print "Error: missing VG name param" + print("Error: missing VG name param") return 1 if not lvutil._checkVG(vgName): - print "Error: VG %s not found" % vgName + print("Error: VG %s not found" % vgName) return 1 j = Journaler(lvmcache.LVMCache(vgName)) if j.get("clone", "1"): - print "get non-existing failed" + print("get non-existing failed") return 1 j.create("clone", "1", "a") val = j.get("clone", "1") if val != "a": - print "create-get failed" + print("create-get failed") return 1 j.remove("clone", "1") if j.get("clone", "1"): - print "remove failed" + print("remove failed") return 1 j.create("modify", "X", "831_3") j.create("modify", "Z", "831_4") j.create("modify", "Y", "53_0") val = j.get("modify", "X") if val != "831_3": - print "create underscore_val failed" + print("create underscore_val failed") return 1 val = j.get("modify", "Y") if val != "53_0": - print "create multiple id's failed" + print("create multiple id's failed") return 1 entries = j.getAll("modify") if not entries.get("X") or not entries.get("Y") or \ entries["X"] != "831_3" or entries["Y"] != "53_0": - print "getAll failed: %s" % entries + print("getAll failed: %s" % entries) return 1 j.remove("modify", "X") val = j.getAll("modify") if val.get("X") or not val.get("Y") or val["Y"] != "53_0": - print "remove(X) failed" + print("remove(X) failed") return 1 j.remove("modify", "Y") j.remove("modify", "Z") if j.get("modify", "Y"): - print "remove(Y) failed" + print("remove(Y) failed") return 1 if j.get("modify", "Z"): - print "remove(Z) failed" + print("remove(Z) failed") return 1 - print "All tests passed" + print("All tests passed") return 0 if __name__ == '__main__': diff --git a/drivers/lcache.py b/drivers/lcache.py index 21e88be80..b79091482 100755 --- a/drivers/lcache.py +++ b/drivers/lcache.py @@ -15,6 +15,7 @@ # along 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 os import blktap2 import glob @@ -265,7 +266,7 @@ def _fast_find_tapdisks(cls): try: stats = tapdisk.stats() - except blktap2.TapCtl.CommandFailure, e: + except blktap2.TapCtl.CommandFailure as e: if e.errno != errno.ENOENT: raise continue # shut down @@ -340,11 +341,9 @@ def xapi_stats(self): def usage(stream): if prog == 'tapdisk-cache-stats': - print >>stream, \ - "usage: tapdisk-cache-stats []" + print("usage: tapdisk-cache-stats []", file=stream) else: - print >>stream, \ - "usage: %s sr.{stats|topology} []" % prog + print("usage: %s sr.{stats|topology} []" % prog, file=stream) def usage_error(): usage(sys.stderr) @@ -376,21 +375,21 @@ def usage_error(): d = cache_sr.xapi_stats() for item in d.iteritems(): - print "%s=%s" % item + print("%s=%s" % item) elif method == 'topology': parents = cache_sr.fast_scan_topology() for parent in parents: - print parent, "hits/miss=%s total=%s" % \ - (parent.vdi_stats(), parent.vdi_stats_total()) + print(parent, "hits/miss=%s total=%s" % \ + (parent.vdi_stats(), parent.vdi_stats_total())) pprint(parent.stats) for leaf in parent.leaves: - print leaf, "hits/miss=%s" % str(leaf.vdi_stats()) + print(leaf, "hits/miss=%s" % str(leaf.vdi_stats())) pprint(leaf.stats) - print "sr.total=%s" % str(cache_sr.vdi_stats_total()) + print("sr.total=%s" % str(cache_sr.vdi_stats_total())) else: usage_error() diff --git a/drivers/lock.py b/drivers/lock.py index db52d5804..b1c8c0bae 100755 --- a/drivers/lock.py +++ b/drivers/lock.py @@ -119,7 +119,7 @@ def _mkdirs(path): return try: os.makedirs(path) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise LockException("Failed to makedirs(%s)" % path) _mkdirs = staticmethod(_mkdirs) @@ -129,7 +129,7 @@ def _unlink(path): util.SMlog("lock: unlinking lock file %s" % path) try: os.unlink(path) - except Exception, e: + except Exception as e: util.SMlog("Failed to unlink(%s): %s" % (path, e)) _unlink = staticmethod(_unlink) @@ -138,7 +138,7 @@ def _rmdir(path): util.SMlog("lock: removing lock dir %s" % path) try: os.rmdir(path) - except Exception, e: + except Exception as e: util.SMlog("Failed to rmdir(%s): %s" % (path, e)) _rmdir = staticmethod(_rmdir) @@ -175,7 +175,7 @@ def _open(self): try: self._open_lockfile() - except IOError, e: + except IOError as e: # If another lock within the namespace has already # cleaned up the namespace by removing the directory, # _open_lockfile raises an ENOENT, in this case we retry. diff --git a/drivers/lvhdutil.py b/drivers/lvhdutil.py index 8158cbe1a..7846f7ba8 100755 --- a/drivers/lvhdutil.py +++ b/drivers/lvhdutil.py @@ -17,6 +17,7 @@ """Helper functions for LVHD SR. This module knows about RAW and VHD VDI's that live in LV's.""" +from __future__ import print_function import os @@ -353,4 +354,4 @@ def setInnerNodeRefcounts(lvmCache, srUuid): util.logException("setInnerNodeRefcounts") else: util.SMlog("Invalid usage") - print "Usage: %s fixrefcounts " % sys.argv[0] + print("Usage: %s fixrefcounts " % sys.argv[0]) diff --git a/drivers/lvutil.py b/drivers/lvutil.py index a5f6a6270..471f420e4 100755 --- a/drivers/lvutil.py +++ b/drivers/lvutil.py @@ -235,7 +235,7 @@ def _getVGstats(vgname): stats['physical_utilisation'] = utilisation stats['freespace'] = freespace return stats - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('VDILoad', \ opterr='rvgstats failed error is %d' % inst.code) except ValueError: @@ -254,7 +254,7 @@ def _getPVstats(dev): stats['physical_utilisation'] = utilisation stats['freespace'] = freespace return stats - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('VDILoad', \ opterr='pvstats failed error is %d' % inst.code) except ValueError: @@ -302,11 +302,11 @@ def scan_srlist(prefix, root): try: sr_uuid = _get_sr_uuid(dev, [prefix]).strip(' \n') if len(sr_uuid): - if VGs.has_key(sr_uuid): + if sr_uuid in VGs: VGs[sr_uuid] += ",%s" % dev else: VGs[sr_uuid] = dev - except Exception, e: + except Exception as e: util.logException("exception (ignored): %s" % e) continue return VGs @@ -441,14 +441,14 @@ def createVG(root, vgname): cmd = [util.CMD_DD, "if=/dev/zero", "of=%s" % dev, "bs=1M", "count=10", "oflag=direct"] util.pread2(cmd) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code == errno.EPERM: try: # Overwrite the disk header, try normal IO cmd = [util.CMD_DD, "if=/dev/zero", "of=%s" % dev, "bs=1M", "count=10"] util.pread2(cmd) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMWrite', \ opterr='device %s' % dev) else: @@ -458,7 +458,7 @@ def createVG(root, vgname): if not (dev == rootdev): try: cmd_lvm([CMD_PVCREATE, "-ff", "-y", "--metadatasize", "10M", dev]) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMPartCreate', opterr='error is %d' % inst.code) @@ -472,7 +472,7 @@ def createVG(root, vgname): for dev in root.split(',')[1:]: try: cmd_lvm([CMD_VGEXTEND, vgname, dev]) - except util.CommandException, inst: + except util.CommandException as inst: # One of the PV args failed, delete SR try: cmd_lvm([CMD_VGREMOVE, vgname]) @@ -482,7 +482,7 @@ def createVG(root, vgname): try: cmd_lvm([CMD_VGCHANGE, "-an", vgname]) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMUnMount', opterr='errno is %d' % inst.code) # End block @@ -495,7 +495,7 @@ def removeVG(root, vgname): if txt.find(vgname) == -1: raise xs_errors.XenError('LVMNoVolume', \ opterr='volume is %s' % vgname) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('PVSfailed', \ opterr='error is %d' % inst.code) @@ -504,14 +504,14 @@ def removeVG(root, vgname): for dev in root.split(','): cmd_lvm([CMD_PVREMOVE, dev]) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('LVMDelete', \ opterr='errno is %d' % inst.code) def resizePV(dev): try: cmd_lvm([CMD_PVRESIZE, dev]) - except util.CommandException, inst: + except util.CommandException as inst: util.SMlog("Failed to grow the PV, non-fatal") def setActiveVG(path, active): @@ -539,7 +539,7 @@ def remove(path, config_param=None): try: _remove(path, config_param) break - except util.CommandException, e: + except util.CommandException as e: if i >= LVM_FAIL_RETRIES - 1: raise util.SMlog("*** lvremove failed on attempt #%d" % i) @@ -643,7 +643,7 @@ def _checkActive(path): try: util.SMlog("_checkActive: attempt to create the symlink manually.") os.symlink(mapperPath, path) - except OSError, e: + except OSError as e: util.SMlog("ERROR: failed to symlink!") if e.errno != errno.EEXIST: raise @@ -666,7 +666,7 @@ def _lvmBugCleanup(path): try: util.pread(cmd_st, expect_rc=1) - except util.CommandException, e: + except util.CommandException as e: if e.code == 0: nodeExists = True @@ -682,7 +682,7 @@ def _lvmBugCleanup(path): try: util.pread2(cmd_rm) break - except util.CommandException, e: + except util.CommandException as e: if i < LVM_FAIL_RETRIES - 1: util.SMlog("Failed on try %d, retrying" % i) try: @@ -724,7 +724,7 @@ def removeDevMapperEntry(path, strict=True): cmd = [CMD_DMSETUP, "remove", path] cmd_lvm(cmd) return True - except Exception, e: + except Exception as e: if not strict: cmd = [CMD_DMSETUP, "status", path] try: diff --git a/drivers/metadata.py b/drivers/metadata.py index 224fe512a..29a0379a5 100755 --- a/drivers/metadata.py +++ b/drivers/metadata.py @@ -18,6 +18,7 @@ # Metadata VDI format # +from __future__ import print_function from xml.dom import minidom, Node import struct import sys, string @@ -146,8 +147,8 @@ def writeXMLtoFile(path, dict): def main(): path = sys.argv[1] xml = retrieveXMLfromFile(path) - print xml - print _parseXML(xml) + print(xml) + print(_parseXML(xml)) if __name__ == '__main__': main() diff --git a/drivers/mpath_cli.py b/drivers/mpath_cli.py index 95051f02b..953c027ef 100755 --- a/drivers/mpath_cli.py +++ b/drivers/mpath_cli.py @@ -17,6 +17,7 @@ # # Talk to the multipathd cli +from __future__ import print_function import util import re import exceptions @@ -27,7 +28,7 @@ def __init__(self): return def __str__(self): - print "","MPath CLI failed" + print("","MPath CLI failed") mpathcmd = ["/usr/sbin/multipathd","-k"] diff --git a/drivers/mpathcount.py b/drivers/mpathcount.py index 6577c7b12..11d5253c2 100755 --- a/drivers/mpathcount.py +++ b/drivers/mpathcount.py @@ -15,6 +15,7 @@ # along 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 util import time, os, sys, re import xs_errors @@ -145,11 +146,11 @@ def update_config(key, SCSIid, entry, remove, add, mpp_path_update = False): def get_SCSIidlist(devconfig, sm_config): SCSIidlist = [] - if sm_config.has_key('SCSIid'): + if 'SCSIid' in sm_config: SCSIidlist = sm_config['SCSIid'].split(',') - elif devconfig.has_key('SCSIid'): + elif 'SCSIid' in devconfig: SCSIidlist.append(devconfig['SCSIid']) - elif devconfig.has_key('provider'): + elif 'provider' in devconfig: SCSIidlist.append(devconfig['ScsiId']) else: for key in sm_config: @@ -169,7 +170,7 @@ def check_root_disk(config, maps, remove, add): util.SMlog("Matched SCSIid %s, updating " \ " Host.other-config:mpath-boot " % i) key="mpath-boot" - if not config.has_key(key): + if key not in config: update_config(key, i, "", remove, add) else: update_config(key, i, config[key], remove, add) @@ -190,7 +191,7 @@ def check_devconfig(devconfig, sm_config, config, remove, add): util.SMlog("Matched SCSIid, updating entry %s" % str(mpp_entry)) update_config(key, i, mpp_entry, remove, add, mpp_path_update) else: - if not config.has_key(key): + if key not in config: update_config(key, i, "", remove, add) else: update_config(key, i, config[key], remove, add) @@ -207,7 +208,7 @@ def check_devconfig(devconfig, sm_config, config, remove, add): try: session = util.get_localAPI_session() except: - print "Unable to open local XAPI session" + print("Unable to open local XAPI session") sys.exit(-1) localhost = session.xenapi.host.get_by_uuid(get_localhost_uuid()) diff --git a/drivers/mpathutil.py b/drivers/mpathutil.py index 13fffcc42..b5acb26b1 100644 --- a/drivers/mpathutil.py +++ b/drivers/mpathutil.py @@ -15,6 +15,7 @@ # along 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 import mpath_cli import time @@ -23,24 +24,24 @@ def list(): maps = mpath_cli.list_maps() for m in maps: - print m + print(m) def wait_for_multipathd(): for i in range(0,120): if mpath_cli.is_working(): return time.sleep(1) - print "Unable to contact Multipathd daemon" + print("Unable to contact Multipathd daemon") sys.exit(-1) def status(): for line in (mpath_cli.get_all_topologies()): - print line + print(line) def usage(): - print "Usage:"; - print "%s list" % sys.argv[0] - print "%s status" % sys.argv[0] + print("Usage:"); + print("%s list" % sys.argv[0]) + print("%s status" % sys.argv[0]) def main(): diff --git a/drivers/mpp_mpathutil.py b/drivers/mpp_mpathutil.py index 055e57d60..b43974a98 100755 --- a/drivers/mpp_mpathutil.py +++ b/drivers/mpp_mpathutil.py @@ -15,6 +15,7 @@ # along 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 import os import util @@ -50,7 +51,7 @@ def get_pathinfo(scsi_id, verbose = False): luninfo = get_luninfo(scsi_id) (rc,stdout,stderr) = query_pathdata(scsi_id, luninfo) if verbose: - print stdout + print(stdout) return lines = stdout.split('\n') for line in lines: @@ -68,10 +69,10 @@ def get_pathinfo(scsi_id, verbose = False): return (int(total_count), int(active_count)) def usage(): - print "Usage:"; - print "%s pathinfo Counts" % sys.argv[0] - print "%s pathinfo Status" % sys.argv[0] - print "%s luninfo " % sys.argv[0] + print("Usage:"); + print("%s pathinfo Counts" % sys.argv[0]) + print("%s pathinfo Status" % sys.argv[0]) + print("%s luninfo " % sys.argv[0]) def main(): @@ -87,7 +88,7 @@ def main(): if mode == "luninfo": luninfo = get_luninfo(scsi_id) if luninfo: - print luninfo['lunnum'] + print(luninfo['lunnum']) else: if mode == "pathinfo": if len(sys.argv) < 4: @@ -96,9 +97,9 @@ def main(): submode = sys.argv[3] if (submode == "Counts"): (total_count, active_count) = get_pathinfo(scsi_id) - print "Total: %s, Active: %s" % (total_count, active_count) + print("Total: %s, Active: %s" % (total_count, active_count)) elif (submode == "HBTL"): - print query_hbtl(scsi_id) + print(query_hbtl(scsi_id)) elif (submode == "Status"): get_pathinfo(scsi_id, verbose=True) else: diff --git a/drivers/nfs.py b/drivers/nfs.py index 6d0c53768..dd892005c 100644 --- a/drivers/nfs.py +++ b/drivers/nfs.py @@ -68,7 +68,7 @@ def check_server_tcp(server, nfsversion=DEFAULT_NFSVERSION): try: sv = get_supported_nfs_versions(server) return (True if nfsversion in sv else False) - except util.CommandException, inst: + except util.CommandException as inst: raise NfsException("rpcinfo failed or timed out: return code %d" % inst.code) @@ -89,7 +89,7 @@ def check_server_service(server): for i in range(len(services)): if services[i].find("nfs") > 0: return True - except util.CommandException, inst: + except util.CommandException as inst: if not int(inst.code) in errlist: raise @@ -126,7 +126,7 @@ def soft_mount(mountpoint, remoteserver, remotepath, transport, useroptions='', try: if not util.ioretry(lambda: util.isdir(mountpoint)): util.ioretry(lambda: util.makedirs(mountpoint)) - except util.CommandException, inst: + except util.CommandException as inst: raise NfsException("Failed to make directory: code is %d" % inst.code) @@ -136,7 +136,7 @@ def soft_mount(mountpoint, remoteserver, remotepath, transport, useroptions='', if not check_server_service(remoteserver): raise util.CommandException(code=errno.EOPNOTSUPP, reason="No NFS service on host") - except util.CommandException, inst: + except util.CommandException as inst: raise NfsException("Failed to detect NFS service on server %s" % remoteserver) @@ -166,7 +166,7 @@ def soft_mount(mountpoint, remoteserver, remotepath, transport, useroptions='', mountpoint, "-o", options]), errlist=[errno.EPIPE, errno.EIO], maxretry=2, nofail=True) - except util.CommandException, inst: + except util.CommandException as inst: raise NfsException("mount failed with return code %d" % inst.code) @@ -174,13 +174,13 @@ def unmount(mountpoint, rmmountpoint): """Unmount the mounted mountpoint""" try: util.pread(["umount", mountpoint]) - except util.CommandException, inst: + except util.CommandException as inst: raise NfsException("umount failed with return code %d" % inst.code) if rmmountpoint: try: os.rmdir(mountpoint) - except OSError, inst: + except OSError as inst: raise NfsException("rmdir failed with error '%s'" % inst.strerror) @@ -236,7 +236,7 @@ def scan_srlist(path, dconf): subentry.appendChild(textnode) from NFSSR import PROBEVERSION - if dconf.has_key(PROBEVERSION): + if PROBEVERSION in dconf: util.SMlog("Add supported nfs versions to sr-probe") try: supported_versions = get_supported_nfs_versions(dconf.get('server')) @@ -275,7 +275,7 @@ def get_supported_nfs_versions(server): def get_nfs_timeout(other_config): nfs_timeout = 100 - if other_config.has_key('nfs-timeout'): + if 'nfs-timeout' in other_config: val = int(other_config['nfs-timeout']) if val < 1: util.SMlog("Invalid nfs-timeout value: %d" % val) @@ -287,7 +287,7 @@ def get_nfs_timeout(other_config): def get_nfs_retrans(other_config): nfs_retrans = 3 - if other_config.has_key('nfs-retrans'): + if 'nfs-retrans' in other_config: val = int(other_config['nfs-retrans']) if val < 0: util.SMlog("Invalid nfs-retrans value: %d" % val) diff --git a/drivers/plugins/keymanagerutil.py b/drivers/plugins/keymanagerutil.py index 50ca00b93..3c21de785 100755 --- a/drivers/plugins/keymanagerutil.py +++ b/drivers/plugins/keymanagerutil.py @@ -7,6 +7,7 @@ This key store is backed by a file stored on disk in dom0, and helper functions are provided to manipulate it. """ +from __future__ import print_function import base64 import os diff --git a/drivers/refcounter.py b/drivers/refcounter.py index 0e4c89522..3bd8dabb5 100644 --- a/drivers/refcounter.py +++ b/drivers/refcounter.py @@ -24,6 +24,7 @@ # +from __future__ import print_function import os import util from lock import Lock @@ -172,7 +173,7 @@ def _createNamespace(ns): nsDir = os.path.join(RefCounter.BASE_DIR, ns) try: os.makedirs(nsDir) - except OSError, e: + except OSError as e: if e.errno != errno.EEXIST: raise RefCounterException("failed to makedirs '%s' (%s)" % \ (nsDir, e)) @@ -190,7 +191,7 @@ def _removeObject(ns, obj): try: os.rmdir(nsDir) - except OSError, e: + except OSError as e: namespaceAlreadyCleanedUp = e.errno == errno.ENOENT newObjectAddedToNamespace = e.errno == errno.ENOTEMPTY @@ -236,7 +237,7 @@ def _writeCount(fn, count, binaryCount): f.write("%d %d\n" % (count, binaryCount)) f.close() return True - except IOError, e: + except IOError as e: fileNotFound = e.errno == errno.ENOENT if fileNotFound: return False @@ -253,283 +254,283 @@ def _runTests(): # A (cnt, bcnt) = RefCounter.check("X", "A") if cnt != 0 or bcnt != 0: - print "Error: check = %d != 0 in the beginning" % cnt + print("Error: check = %d != 0 in the beginning" % cnt) return -1 cnt = RefCounter.get("X", False, "A") if cnt != 1: - print "Error: count = %d != 1 after first get()" % cnt + print("Error: count = %d != 1 after first get()" % cnt) return -1 (cnt, bcnt) = RefCounter.check("X", "A") if cnt != 1: - print "Error: check = %d != 1 after first get()" % cnt + print("Error: check = %d != 1 after first get()" % cnt) return -1 cnt = RefCounter.put("X", False, "A") if cnt != 0: - print "Error: count = %d != 0 after get-put" % cnt + print("Error: count = %d != 0 after get-put" % cnt) return -1 (cnt, bcnt) = RefCounter.check("X", "A") if cnt != 0: - print "Error: check = %d != 0 after get-put" % cnt + print("Error: check = %d != 0 after get-put" % cnt) return -1 cnt = RefCounter.get("X", False, "A") if cnt != 1: - print "Error: count = %d != 1 after get-put-get" % cnt + print("Error: count = %d != 1 after get-put-get" % cnt) return -1 cnt = RefCounter.get("X", False, "A") if cnt != 2: - print "Error: count = %d != 2 after second get()" % cnt + print("Error: count = %d != 2 after second get()" % cnt) return -1 cnt = RefCounter.get("X", False, "A") if cnt != 3: - print "Error: count = %d != 3 after third get()" % cnt + print("Error: count = %d != 3 after third get()" % cnt) return -1 (cnt, bcnt) = RefCounter.check("X", "A") if cnt != 3: - print "Error: check = %d != 3 after third get()" % cnt + print("Error: check = %d != 3 after third get()" % cnt) return -1 cnt = RefCounter.put("Y", False, "A") if cnt != 0: - print "Error: count = %d != 0 after first put()" % cnt + print("Error: count = %d != 0 after first put()" % cnt) return -1 (cnt, bcnt) = RefCounter.check("Y", "A") if cnt != 0: - print "Error: check = %d != 0 after first put()" % cnt + print("Error: check = %d != 0 after first put()" % cnt) return -1 cnt = RefCounter.put("X", False, "A") if cnt != 2: - print "Error: count = %d != 2 after 3get-1put" % cnt + print("Error: count = %d != 2 after 3get-1put" % cnt) return -1 cnt = RefCounter.put("X", False, "A") if cnt != 1: - print "Error: count = %d != 1 after 3get-2put" % cnt + print("Error: count = %d != 1 after 3get-2put" % cnt) return -1 cnt = RefCounter.get("X", False, "A") if cnt != 2: - print "Error: count = %d != 2 after 4get-2put" % cnt + print("Error: count = %d != 2 after 4get-2put" % cnt) return -1 (cnt, bcnt) = RefCounter.check("X", "A") if cnt != 2: - print "Error: check = %d != 2 after 4get-2put" % cnt + print("Error: check = %d != 2 after 4get-2put" % cnt) return -1 cnt = RefCounter.put("X", False, "A") if cnt != 1: - print "Error: count = %d != 0 after 4get-3put" % cnt + print("Error: count = %d != 0 after 4get-3put" % cnt) return -1 cnt = RefCounter.put("X", False, "A") if cnt != 0: - print "Error: count = %d != 0 after 4get-4put" % cnt + print("Error: count = %d != 0 after 4get-4put" % cnt) return -1 (cnt, bcnt) = RefCounter.check("X", "A") if cnt != 0: - print "Error: check = %d != 0 after 4get-4put" % cnt + print("Error: check = %d != 0 after 4get-4put" % cnt) return -1 # B cnt = RefCounter.put("Z", False, "B") if cnt != 0: - print "Error: count = %d != 0 after new put()" % cnt + print("Error: count = %d != 0 after new put()" % cnt) return -1 cnt = RefCounter.get("Z", False, "B") if cnt != 1: - print "Error: count = %d != 1 after put-get" % cnt + print("Error: count = %d != 1 after put-get" % cnt) return -1 cnt = RefCounter.put("Z", False, "B") if cnt != 0: - print "Error: count = %d != 0 after put-get-put" % cnt + print("Error: count = %d != 0 after put-get-put" % cnt) return -1 (cnt, bcnt) = RefCounter.check("Z", "B") if cnt != 0: - print "Error: check = %d != 0 after put-get-put" % cnt + print("Error: check = %d != 0 after put-get-put" % cnt) return -1 cnt = RefCounter.get("Z", False, "B") if cnt != 1: - print "Error: count = %d != 1 after put-get-put-get" % cnt + print("Error: count = %d != 1 after put-get-put-get" % cnt) return -1 (cnt, bcnt) = RefCounter.check("Z", "B") if cnt != 1: - print "Error: check = %d != 1 after put-get-put-get" % cnt + print("Error: check = %d != 1 after put-get-put-get" % cnt) return -1 # set (cnt, bcnt) = RefCounter.check("a/b") if cnt != 0: - print "Error: count = %d != 0 initially" % cnt + print("Error: count = %d != 0 initially" % cnt) return -1 RefCounter.set("a/b", 2, 0) (cnt, bcnt) = RefCounter.check("a/b") if cnt != 2 or bcnt != 0: - print "Error: count = (%d,%d) != (2,0) after set(2,0)" % (cnt, bcnt) + print("Error: count = (%d,%d) != (2,0) after set(2,0)" % (cnt, bcnt)) return -1 cnt = RefCounter.put("a/b", False) if cnt != 1: - print "Error: count = %d != 1 after set(2)-put" % cnt + print("Error: count = %d != 1 after set(2)-put" % cnt) return -1 cnt = RefCounter.get("a/b", False) if cnt != 2: - print "Error: count = %d != 2 after set(2)-put-get" % cnt + print("Error: count = %d != 2 after set(2)-put-get" % cnt) return -1 RefCounter.set("a/b", 100, 0) (cnt, bcnt) = RefCounter.check("a/b") if cnt != 100 or bcnt != 0: - print "Error: cnt,bcnt = (%d,%d) != (100,0) after set(100,0)" % \ - (cnt, bcnt) + print("Error: cnt,bcnt = (%d,%d) != (100,0) after set(100,0)" % \ + (cnt, bcnt)) return -1 cnt = RefCounter.get("a/b", False) if cnt != 101: - print "Error: count = %d != 101 after get" % cnt + print("Error: count = %d != 101 after get" % cnt) return -1 RefCounter.set("a/b", 100, 1) (cnt, bcnt) = RefCounter.check("a/b") if cnt != 100 or bcnt != 1: - print "Error: cnt,bcnt = (%d,%d) != (100,1) after set(100,1)" % \ - (cnt, bcnt) + print("Error: cnt,bcnt = (%d,%d) != (100,1) after set(100,1)" % \ + (cnt, bcnt)) return -1 RefCounter.reset("a/b") (cnt, bcnt) = RefCounter.check("a/b") if cnt != 0: - print "Error: check = %d != 0 after reset" % cnt + print("Error: check = %d != 0 after reset" % cnt) return -1 # binary cnt = RefCounter.get("A", True) if cnt != 1: - print "Error: count = %d != 1 after get(bin)" % cnt + print("Error: count = %d != 1 after get(bin)" % cnt) return -1 cnt = RefCounter.get("A", True) if cnt != 1: - print "Error: count = %d != 1 after get(bin)*2" % cnt + print("Error: count = %d != 1 after get(bin)*2" % cnt) return -1 cnt = RefCounter.put("A", True) if cnt != 0: - print "Error: count = %d != 0 after get(bin)*2-put(bin)" % cnt + print("Error: count = %d != 0 after get(bin)*2-put(bin)" % cnt) return -1 cnt = RefCounter.put("A", True) if cnt != 0: - print "Error: count = %d != 0 after get(bin)*2-put(bin)*2" % cnt + print("Error: count = %d != 0 after get(bin)*2-put(bin)*2" % cnt) return -1 try: RefCounter.set("A", 0, 2) - print "Error: set(0,2) was allowed" + print("Error: set(0,2) was allowed") return -1 except RefCounterException: pass cnt = RefCounter.get("A", True) if cnt != 1: - print "Error: count = %d != 1 after get(bin)" % cnt + print("Error: count = %d != 1 after get(bin)" % cnt) return -1 cnt = RefCounter.get("A", False) if cnt != 2: - print "Error: count = %d != 2 after get(bin)-get" % cnt + print("Error: count = %d != 2 after get(bin)-get" % cnt) return -1 cnt = RefCounter.get("A", False) if cnt != 3: - print "Error: count = %d != 3 after get(bin)-get-get" % cnt + print("Error: count = %d != 3 after get(bin)-get-get" % cnt) return -1 cnt = RefCounter.get("A", True) if cnt != 3: - print "Error: count = %d != 3 after get(bin)-get*2-get(bin)" % cnt + print("Error: count = %d != 3 after get(bin)-get*2-get(bin)" % cnt) return -1 cnt = RefCounter.put("A", False) if cnt != 2: - print "Error: count = %d != 2 after get(bin)*2-get*2-put" % cnt + print("Error: count = %d != 2 after get(bin)*2-get*2-put" % cnt) return -1 cnt = RefCounter.put("A", True) if cnt != 1: - print "Error: cnt = %d != 1 after get(b)*2-get*2-put-put(b)" % cnt + print("Error: cnt = %d != 1 after get(b)*2-get*2-put-put(b)" % cnt) return -1 cnt = RefCounter.put("A", False) if cnt != 0: - print "Error: cnt = %d != 0 after get(b)*2-get*2-put*2-put(b)" % cnt + print("Error: cnt = %d != 0 after get(b)*2-get*2-put*2-put(b)" % cnt) return -1 # names cnt = RefCounter.get("Z", False) if cnt != 1: - print "Error: count = %d != 1 after get (no ns 1)" % cnt + print("Error: count = %d != 1 after get (no ns 1)" % cnt) return -1 cnt = RefCounter.get("Z/", False) if cnt != 1: - print "Error: count = %d != 1 after get (no ns 2)" % cnt + print("Error: count = %d != 1 after get (no ns 2)" % cnt) return -1 cnt = RefCounter.get("/Z", False) if cnt != 1: - print "Error: count = %d != 1 after get (no ns 3)" % cnt + print("Error: count = %d != 1 after get (no ns 3)" % cnt) return -1 cnt = RefCounter.get("/Z/*/?/\\", False) if cnt != 1: - print "Error: count = %d != 1 after get (no ns 4)" % cnt + print("Error: count = %d != 1 after get (no ns 4)" % cnt) return -1 cnt = RefCounter.get("Z", False) if cnt != 2: - print "Error: count = %d != 2 after get (no ns 1)" % cnt + print("Error: count = %d != 2 after get (no ns 1)" % cnt) return -1 cnt = RefCounter.get("Z/", False) if cnt != 2: - print "Error: count = %d != 2 after get (no ns 2)" % cnt + print("Error: count = %d != 2 after get (no ns 2)" % cnt) return -1 cnt = RefCounter.get("/Z", False) if cnt != 2: - print "Error: count = %d != 2 after get (no ns 3)" % cnt + print("Error: count = %d != 2 after get (no ns 3)" % cnt) return -1 cnt = RefCounter.get("/Z/*/?/\\", False) if cnt != 2: - print "Error: count = %d != 2 after get (no ns 4)" % cnt + print("Error: count = %d != 2 after get (no ns 4)" % cnt) return -1 # resetAll RefCounter.resetAll("B") cnt = RefCounter.get("Z", False, "B") if cnt != 1: - print "Error: count = %d != 1 after resetAll-get" % cnt + print("Error: count = %d != 1 after resetAll-get" % cnt) return -1 cnt = RefCounter.get("Z", False, "C") if cnt != 1: - print "Error: count = %d != 1 after C.get" % cnt + print("Error: count = %d != 1 after C.get" % cnt) return -1 RefCounter.resetAll("B") cnt = RefCounter.get("Z", False, "B") if cnt != 1: - print "Error: count = %d != 1 after second resetAll-get" % cnt + print("Error: count = %d != 1 after second resetAll-get" % cnt) return -1 cnt = RefCounter.get("Z", False, "C") if cnt != 2: - print "Error: count = %d != 2 after second C.get" % cnt + print("Error: count = %d != 2 after second C.get" % cnt) return -1 RefCounter.resetAll("D") RefCounter.resetAll() cnt = RefCounter.put("Z", False, "B") if cnt != 0: - print "Error: count = %d != 0 after resetAll-put" % cnt + print("Error: count = %d != 0 after resetAll-put" % cnt) return -1 cnt = RefCounter.put("Z", False, "C") if cnt != 0: - print "Error: count = %d != 0 after C.resetAll-put" % cnt + print("Error: count = %d != 0 after C.resetAll-put" % cnt) return -1 RefCounter.resetAll() @@ -539,10 +540,10 @@ def _runTests(): if __name__ == '__main__': - print "Running unit tests..." + print("Running unit tests...") try: if RefCounter._runTests() == 0: - print "All done, no errors" - except RefCounterException, e: - print "FAIL: Got exception: %s" % e + print("All done, no errors") + except RefCounterException as e: + print("FAIL: Got exception: %s" % e) raise diff --git a/drivers/resetvdis.py b/drivers/resetvdis.py index e89cc6f2c..3c5665a58 100755 --- a/drivers/resetvdis.py +++ b/drivers/resetvdis.py @@ -18,6 +18,7 @@ # Clear the attach status for all VDIs in the given SR on this host. # Additionally, reset the paused state if this host is the master. +from __future__ import print_function import cleanup import util import lock @@ -73,11 +74,11 @@ def reset_vdi(session, vdi_uuid, force, term_output=True, writable=True): host_rec = session.xenapi.host.get_record(host_ref) host_uuid = host_rec["uuid"] host_str = "%s (%s)" % (host_uuid, host_rec["name_label"]) - except XenAPI.Failure, e: + except XenAPI.Failure as e: msg = "Invalid host: %s (%s)" % (host_ref, e) util.SMlog(msg) if term_output: - print msg + print(msg) host_invalid=True if host_invalid: @@ -86,7 +87,7 @@ def reset_vdi(session, vdi_uuid, force, term_output=True, writable=True): (val, vdi_uuid, host_str) util.SMlog(msg) if term_output: - print msg + print(msg) continue if force: @@ -95,7 +96,7 @@ def reset_vdi(session, vdi_uuid, force, term_output=True, writable=True): (val, vdi_uuid, host_str) util.SMlog(msg) if term_output: - print msg + print(msg) continue ret = session.xenapi.host.call_plugin( @@ -105,8 +106,8 @@ def reset_vdi(session, vdi_uuid, force, term_output=True, writable=True): util.SMlog("VDI %s is still open on host %s, not resetting" % \ (vdi_uuid, host_str)) if term_output: - print "ERROR: VDI %s is still open on host %s" % \ - (vdi_uuid, host_str) + print("ERROR: VDI %s is still open on host %s" % \ + (vdi_uuid, host_str)) if writable: return False else: @@ -117,25 +118,25 @@ def reset_vdi(session, vdi_uuid, force, term_output=True, writable=True): (val, vdi_uuid, host_str) util.SMlog(msg) if term_output: - print msg + print(msg) if not host_ref: msg = "VDI %s is not marked as attached anywhere, nothing to do" \ % vdi_uuid util.SMlog(msg) if term_output: - print msg + print(msg) return clean def usage(): - print "Usage:" - print "all [--master]" - print "single [--force]" - print - print "*WARNING!* calling with 'all' on an attached SR, or using " + \ + print("Usage:") + print("all [--master]") + print("single [--force]") + print() + print("*WARNING!* calling with 'all' on an attached SR, or using " + \ "--force may cause DATA CORRUPTION if the VDI is still " + \ "attached somewhere. Always manually double-check that " + \ - "the VDI is not in use before running this script." + "the VDI is not in use before running this script.") sys.exit(1) if __name__ == '__main__': diff --git a/drivers/scsi_host_rescan.py b/drivers/scsi_host_rescan.py index 660ba7538..7122bc403 100755 --- a/drivers/scsi_host_rescan.py +++ b/drivers/scsi_host_rescan.py @@ -42,7 +42,7 @@ def _rescan_hostID(host): f.close() # allow some time for undiscovered LUNs/channels to appear time.sleep(2) - except Exception, e: + except Exception as e: util.SMlog("Failed to perform full rescan of host: %s. "\ "Error: %s" % (host, str(e))) raise Exception(str(e)) @@ -116,7 +116,7 @@ def rescan(hostid): if not tryRescan: break - except Exception, e: + except Exception as e: util.SMlog("Failed to perform rescan of host: %s. "\ "Error: %s" % (hostid, str(e))) finally: diff --git a/drivers/scsiutil.py b/drivers/scsiutil.py index 6bf322d33..41671028d 100755 --- a/drivers/scsiutil.py +++ b/drivers/scsiutil.py @@ -18,6 +18,7 @@ # Miscellaneous scsi utility functions # +from __future__ import print_function import util import os import re @@ -165,10 +166,10 @@ def scsi_dev_ctrl(ids, cmd): (cmd, ids[1],ids[2],ids[3],ids[4]) util.SMlog(str) f=open('/proc/scsi/scsi', 'w') - print >>f, str + print(str, file=f) f.close() return - except IOError, e: + except IOError as e: util.SMlog("SCSI_DEV_CTRL: Failure, %s [%d]" % (e.strerror,e.errno)) if f is not None: f.close() @@ -646,10 +647,10 @@ def remove_stale_luns(hostids, lunid, expectedPath, mpath): try: path = os.path.basename(os.path.realpath(lun)) mpath_cli.remove_path(path) - except Exception, e: + except Exception as e: util.SMlog("Failed to remove path %s, ignoring "\ "exception as path may not be present." % path) - except Exception, e: + except Exception as e: util.SMlog("Exception removing stale LUNs, new devices may not come"\ " up properly! Error: %s" % str(e)) diff --git a/drivers/srmetadata.py b/drivers/srmetadata.py index edbe6b02c..b77dc10e5 100755 --- a/drivers/srmetadata.py +++ b/drivers/srmetadata.py @@ -78,13 +78,13 @@ def open_file(path, write = False): if write: try: file_p = os.open(path, os.O_RDWR ) - except OSError, e: + except OSError as e: raise OSError("Failed to open file %s for read-write. Error: %s" % \ (path, (e.errno))) else: try: file_p = os.open(path, os.O_RDONLY) - except OSError, e: + except OSError as e: raise OSError("Failed to open file %s for read. Error: %s" % \ (path, (e.errno))) return file_p @@ -96,7 +96,7 @@ def file_write_wrapper(fd, offset, blocksize, data, length): newlength = length + (blocksize - length % blocksize) os.lseek(fd, offset, os.SEEK_SET) result = os.write(fd, data + ' ' * (newlength - length)) - except OSError, e: + except OSError as e: raise OSError("Failed to write file with params %s. Error: %s" % \ ([fd, offset, blocksize, data, length], \ (e.errno))) @@ -106,7 +106,7 @@ def file_read_wrapper(fd, offset, bytesToRead, min_block_size): try: os.lseek(fd, offset, os.SEEK_SET) result = os.read(fd, bytesToRead) - except OSError, e: + except OSError as e: raise OSError("Failed to read file with params %s. Error: %s" % \ ([fd, offset, min_block_size, bytesToRead], \ (e.errno))) @@ -181,7 +181,7 @@ def updateLengthInHeader(fd, length, major = metadata.MD_MAJOR, \ # Now write the new length file_write_wrapper(fd, 0, min_block_size, updated_md, len(updated_md)) - except Exception, e: + except Exception as e: util.SMlog("Exception updating metadata length with length: %d." "Error: %s" % (length, str(e))) raise @@ -194,7 +194,7 @@ def getMetadataLength(fd): hdr = unpackHeader(sector1) len = int(hdr[1]) return len - except Exception, e: + except Exception as e: util.SMlog("Exception getting metadata length: " "Error: %s" % str(e)) raise @@ -209,7 +209,7 @@ def requiresUpgrade(path): try: if metadata.requiresUpgrade(path): pre_boston_upgrade = True - except Exception, e: + except Exception as e: util.SMlog("This looks like a 6.0 or later pool, try checking " \ "for upgrade using the new metadata header format. " \ "Error: %s" % str(e)) @@ -231,7 +231,7 @@ def requiresUpgrade(path): elif mdmajor == metadata.MD_MAJOR and mdminor < metadata.MD_MINOR: boston_upgrade = True - except Exception, e: + except Exception as e: util.SMlog("Exception checking header version, upgrading metadata."\ " Error: %s" % str(e)) return True @@ -273,7 +273,7 @@ def getMetadata(self,params = {}): # Maybe there is no metadata yet pass - except Exception, e: + except Exception as e: util.SMlog('Exception getting metadata. Error: %s' % str(e)) raise xs_errors.XenError('MetadataError', \ opterr='%s' % str(e)) @@ -283,7 +283,7 @@ def getMetadata(self,params = {}): def writeMetadata(self, sr_info, vdi_info): try: self.writeMetadataInternal(sr_info, vdi_info) - except Exception, e: + except Exception as e: util.SMlog('Exception writing metadata. Error: %s' % str(e)) raise xs_errors.XenError('MetadataError', \ opterr='%s' % str(e)) @@ -298,7 +298,7 @@ def findMetadataVDI(self): return vdi_info[offset][UUID_TAG] return None - except Exception, e: + except Exception as e: util.SMlog('Exception checking if SR metadata a metadata VDI.'\ 'Error: %s' % str(e)) raise xs_errors.XenError('MetadataError', \ @@ -333,7 +333,7 @@ def updateMetadata(self, update_map = {}): self.updateSR(update_map) elif objtype == METADATA_OBJECT_TYPE_VDI: self.updateVdi(update_map) - except Exception, e: + except Exception as e: util.SMlog('Error updating Metadata Volume with update' \ 'map: %s. Error: %s' % (update_map, str(e))) raise xs_errors.XenError('MetadataError', \ @@ -343,7 +343,7 @@ def deleteVdiFromMetadata(self, vdi_uuid): util.SMlog("Deleting vdi: %s" % vdi_uuid) try: self.deleteVdi(vdi_uuid) - except Exception, e: + except Exception as e: util.SMlog('Error deleting vdi %s from the metadata. '\ 'Error: %s' % (vdi_uuid, str(e))) raise xs_errors.XenError('MetadataError', \ @@ -353,7 +353,7 @@ def addVdi(self, vdi_info = {}): util.SMlog("Adding VDI with info: %s" % vdi_info) try: self.addVdiInternal(vdi_info) - except Exception, e: + except Exception as e: util.SMlog('Error adding VDI to Metadata Volume with '\ 'update map: %s. Error: %s' % (vdi_info, str(e))) raise xs_errors.XenError('MetadataError', \ @@ -364,7 +364,7 @@ def ensureSpaceIsAvailableForVdis(self, count): count) try: self.spaceAvailableForVdis(count) - except Exception, e: + except Exception as e: raise xs_errors.XenError('MetadataError', \ opterr='%s' % str(e)) @@ -373,7 +373,7 @@ def deleteVdi(self, vdi_uuid, offset = 0): util.SMlog("Entering deleteVdi") try: md = self.getMetadataInternal({'vdi_uuid': vdi_uuid}) - if not md.has_key('offset'): + if 'offset' not in md: util.SMlog("Metadata for VDI %s not present, or already removed, " \ "no further deletion action required." % vdi_uuid) return @@ -389,7 +389,7 @@ def deleteVdi(self, vdi_uuid, offset = 0): self.VDI_INFO_SIZE_IN_SECTORS * SECTOR_SIZE)) except: raise - except Exception, e: + except Exception as e: raise Exception("VDI delete operation failed for "\ "parameters: %s, %s. Error: %s" % \ (self.path, vdi_uuid, str(e))) @@ -398,7 +398,7 @@ def deleteVdi(self, vdi_uuid, offset = 0): def generateVDIsForRange(self, vdi_info, lower, upper, update_map = {}, \ offset = 0): value = '' - if not len(vdi_info.keys()) or not vdi_info.has_key(offset): + if not len(vdi_info.keys()) or offset not in vdi_info: return self.getVdiInfo(update_map) for vdi_offset in vdi_info.keys(): @@ -428,13 +428,13 @@ def addVdiInternal(self, Dict): min_block_size = get_min_blk_size_wrapper(self.fd) mdlength = getMetadataLength(self.fd) md = self.getMetadataInternal({'firstDeleted': 1, 'includeDeletedVdis': 1}) - if not md.has_key('foundDeleted'): + if 'foundDeleted' not in md: md['offset'] = mdlength (md['lower'], md['upper']) = \ getBlockAlignedRange(min_block_size, mdlength, \ SECTOR_SIZE * self.VDI_INFO_SIZE_IN_SECTORS) # If this has created a new VDI, update metadata length - if md.has_key('foundDeleted'): + if 'foundDeleted' in md: value = self.getMetadataToWrite(md['sr_info'], md['vdi_info'], \ md['lower'], md['upper'], Dict, md['offset']) else: @@ -444,13 +444,13 @@ def addVdiInternal(self, Dict): file_write_wrapper(self.fd, md['lower'], min_block_size, \ value, len(value)) - if md.has_key('foundDeleted'): + if 'foundDeleted' in md: updateLengthInHeader(self.fd, mdlength) else: updateLengthInHeader(self.fd, mdlength + \ SECTOR_SIZE * self.VDI_INFO_SIZE_IN_SECTORS) return True - except Exception, e: + except Exception as e: util.SMlog("Exception adding vdi with info: %s. Error: %s" % \ (Dict, str(e))) raise @@ -490,7 +490,7 @@ def getMetadataInternal(self, params = {}): retmap['sr_info'] = metadata._parseXML(parsable_metadata) # At this point we check if an offset has been passed in - if params.has_key('offset'): + if 'offset' in params: upper = getBlockAlignedRange(min_blk_size, params['offset'], \ 0)[1] else: @@ -507,24 +507,24 @@ def getMetadataInternal(self, params = {}): vdi_info_map = metadata._parseXML(parsable_metadata)[VDI_TAG] vdi_info_map[OFFSET_TAG] = offset - if not params.has_key('includeDeletedVdis') and \ + if 'includeDeletedVdis' not in params and \ vdi_info_map[VDI_DELETED_TAG] == '1': offset += SECTOR_SIZE * self.VDI_INFO_SIZE_IN_SECTORS continue - if params.has_key('indexByUuid'): + if 'indexByUuid' in params: ret_vdi_info[vdi_info_map[UUID_TAG]] = vdi_info_map else: ret_vdi_info[offset] = vdi_info_map - if params.has_key('vdi_uuid'): + if 'vdi_uuid' in params: if vdi_info_map[UUID_TAG] == params['vdi_uuid']: retmap['offset'] = offset (lower, upper) = \ getBlockAlignedRange(min_blk_size, offset, \ SECTOR_SIZE * self.VDI_INFO_SIZE_IN_SECTORS) - elif params.has_key('firstDeleted'): + elif 'firstDeleted' in params: if vdi_info_map[VDI_DELETED_TAG] == '1': retmap['foundDeleted'] = 1 retmap['offset'] = offset @@ -538,7 +538,7 @@ def getMetadataInternal(self, params = {}): retmap['upper'] = upper retmap['vdi_info'] = ret_vdi_info return retmap - except Exception, e: + except Exception as e: util.SMlog("Exception getting metadata with params" \ "%s. Error: %s" % (params, str(e))) raise @@ -600,7 +600,7 @@ def updateVdi(self, Dict): md['lower'], md['upper'], Dict, md['offset']) file_write_wrapper(self.fd, md['lower'], min_block_size, value, len(value)) return True - except Exception, e: + except Exception as e: util.SMlog("Exception updating vdi with info: %s. Error: %s" % \ (Dict, str(e))) raise @@ -622,7 +622,7 @@ def writeMetadataInternal(self, sr_info, vdi_info): file_write_wrapper(self.fd, 0, min_block_size, md, len(md)) updateLengthInHeader(self.fd, len(md)) - except Exception, e: + except Exception as e: util.SMlog("Exception writing metadata with info: %s, %s. "\ "Error: %s" % (sr_info, vdi_info, str(e))) raise @@ -653,7 +653,7 @@ def getMetadataToWrite(self, sr_info, vdi_info, lower, upper, update_map, \ value += self.generateVDIsForRange(vdi_info, lower, upper, \ update_map, offset) return value - except Exception, e: + except Exception as e: util.SMlog("Exception generating metadata to write with info: "\ "sr_info: %s, vdi_info: %s, lower: %d, upper: %d, "\ "update_map: %s, offset: %d. Error: %s" % \ @@ -696,7 +696,7 @@ def spaceAvailableForVdis(self, count): } created = self.addVdiInternal(vdi_info) - except IOError, e: + except IOError as e: raise finally: if created: @@ -752,7 +752,7 @@ def getVdiInfo(self, Dict, generateSector = 0): if generateSector == 2 or generateSector == 0: sector2 = '' - if not Dict.has_key(VDI_DELETED_TAG): + if VDI_DELETED_TAG not in Dict: Dict.update({VDI_DELETED_TAG:'0'}) for tag in Dict.keys(): @@ -764,7 +764,7 @@ def getVdiInfo(self, Dict, generateSector = 0): vdi_info += getSector(sector2) return vdi_info - except Exception, e: + except Exception as e: util.SMlog("Exception generating vdi info: %s. Error: %s" % \ (Dict, str(e))) raise @@ -798,7 +798,7 @@ def getSRInfoForSectors(self, sr_info, range): return srinfo - except Exception, e: + except Exception as e: util.SMlog("Exception getting SR info with parameters: sr_info: %s," \ "range: %s. Error: %s" % (sr_info, range, str(e))) raise @@ -832,7 +832,7 @@ def spaceAvailableForVdis(self, count): } created = self.addVdiInternal(vdi_info) - except IOError, e: + except IOError as e: raise finally: if created: @@ -888,7 +888,7 @@ def getVdiInfo(self, Dict, generateSector = 0): if generateSector == 2 or generateSector == 0: sector2 = '' - if not Dict.has_key(VDI_DELETED_TAG): + if VDI_DELETED_TAG not in Dict: Dict.update({VDI_DELETED_TAG:'0'}) for tag in Dict.keys(): @@ -900,7 +900,7 @@ def getVdiInfo(self, Dict, generateSector = 0): vdi_info += getSector(sector2) return vdi_info - except Exception, e: + except Exception as e: util.SMlog("Exception generating vdi info: %s. Error: %s" % \ (Dict, str(e))) raise @@ -932,7 +932,7 @@ def getSRInfoForSectors(self, sr_info, range): return srinfo - except Exception, e: + except Exception as e: util.SMlog("Exception getting SR info with parameters: sr_info: %s," \ "range: %s. Error: %s" % (sr_info, range, str(e))) raise diff --git a/drivers/sysdevice.py b/drivers/sysdevice.py index 8249a1abd..8a365d671 100644 --- a/drivers/sysdevice.py +++ b/drivers/sysdevice.py @@ -78,7 +78,7 @@ def stat(device): device = os.path.join(sys, "device") try: - results["size"] = long(read_whole_file(os.path.join(sys, "size"))[0]) * 512L + results["size"] = long(read_whole_file(os.path.join(sys, "size"))[0]) * 512 except: pass @@ -86,10 +86,10 @@ def stat(device): results["bus_path"] = "" try: device_path = os.readlink(device) - if device_path.find("/usb") <> -1: + if device_path.find("/usb") != -1: results["bus"] = "USB" results["bus_path"] = os.path.basename(device_path) - elif device_path.find("/ide") <> -1: + elif device_path.find("/ide") != -1: results["bus"] = "IDE" results["bus_path"] = os.path.basename(device_path) elif os.readlink(os.path.join(device, "subsystem")).endswith("scsi"): diff --git a/drivers/trim_util.py b/drivers/trim_util.py index ce7d97349..c63e3ca94 100755 --- a/drivers/trim_util.py +++ b/drivers/trim_util.py @@ -73,7 +73,7 @@ def _log_last_triggered(session, sr_uuid): try: sr_ref = session.xenapi.SR.get_by_uuid(sr_uuid) other_config = session.xenapi.SR.get_other_config(sr_ref) - if other_config.has_key(TRIM_LAST_TRIGGERED_KEY): + if TRIM_LAST_TRIGGERED_KEY in other_config: session.xenapi.SR.remove_from_other_config(sr_ref, TRIM_LAST_TRIGGERED_KEY) session.xenapi.SR.add_to_other_config(sr_ref, TRIM_LAST_TRIGGERED_KEY, str(time.time())) except: @@ -126,7 +126,7 @@ def do_trim(session, args): util.SMlog("Stdout is %s" % stdout) util.SMlog("Trim on SR: %s complete. " % sr_uuid) result = str(True) - except util.CommandException, e: + except util.CommandException as e: err_msg = { ERROR_CODE_KEY: 'TrimException', ERROR_MSG_KEY: e.reason diff --git a/drivers/udevSR.py b/drivers/udevSR.py index 14826f9f1..a95aa8657 100755 --- a/drivers/udevSR.py +++ b/drivers/udevSR.py @@ -69,7 +69,7 @@ def get_vdi_location(self, uuid): def load(self, sr_uuid): # First of all, check we've got the correct keys in dconf - if not self.dconf.has_key('location'): + if 'location' not in self.dconf: raise xs_errors.XenError('ConfigLocationMissing') self.sr_vditype = 'phy' # Cache the sm_config @@ -85,7 +85,7 @@ def update(self, sr_uuid): x = udevVDI(self, path) self.vdis[path] = x - the_sum = 0L + the_sum = 0 for vdi in self.vdis.values(): the_sum = the_sum + vdi.size @@ -149,7 +149,7 @@ def load(self, location): self.description = info["hwinfo"] # XXX: what other information can we recover? - if self.sr.sm_config.has_key('type'): + if 'type' in self.sr.sm_config: self.read_only = self.sr.sm_config['type'] == "cd" usb_path = info.get("usb_path") @@ -162,7 +162,7 @@ def load(self, location): raise xs_errors.XenError('VDIUnavailable') break - except OSError, e: + except OSError as e: self.deleted = True def introduce(self, sr_uuid, vdi_uuid): diff --git a/drivers/util.py b/drivers/util.py index 337add2ba..7744661da 100755 --- a/drivers/util.py +++ b/drivers/util.py @@ -18,6 +18,7 @@ # Miscellaneous utility functions # +from __future__ import print_function import os, re, sys, subprocess, shutil, tempfile, signal import time, datetime import errno, socket @@ -36,6 +37,8 @@ import copy import tempfile +from functools import reduce + NO_LOGGING_STAMPFILE='/etc/xensource/no_sm_log' IORETRY_MAX = 20 # retries @@ -246,7 +249,7 @@ def listdir(path, quiet = False): if len(text) == 0: return [] return text.split('\n') - except CommandException, inst: + except CommandException as inst: if inst.code == errno.ENOENT: raise CommandException(errno.EIO, inst.cmd, inst.reason) else: @@ -328,12 +331,12 @@ def ioretry(f, errlist=[errno.EIO], maxretry=IORETRY_MAX, period=IORETRY_PERIOD, while True: try: return f() - except OSError, inst: + except OSError as inst: err = int(inst.errno) inst = CommandException(err, str(f), "OSError") if not err in errlist: raise inst - except CommandException, inst: + except CommandException as inst: if not int(inst.code) in errlist: raise @@ -414,19 +417,19 @@ def SRtoXML(SRlist): textnode = dom.createTextNode(key) e.appendChild(textnode) - if dict.has_key('size'): + if 'size' in dict: e = dom.createElement("Size") entry.appendChild(e) textnode = dom.createTextNode(str(dict['size'])) e.appendChild(textnode) - if dict.has_key('storagepool'): + if 'storagepool' in dict: e = dom.createElement("StoragePool") entry.appendChild(e) textnode = dom.createTextNode(str(dict['storagepool'])) e.appendChild(textnode) - if dict.has_key('aggregate'): + if 'aggregate' in dict: e = dom.createElement("Aggregate") entry.appendChild(e) textnode = dom.createTextNode(str(dict['aggregate'])) @@ -438,7 +441,7 @@ def pathexists(path): try: os.lstat(path) return True - except OSError, inst: + except OSError as inst: if inst.errno == errno.EIO: time.sleep(1) try: @@ -453,7 +456,7 @@ def pathexists(path): def force_unlink(path): try: os.unlink(path) - except OSError, e: + except OSError as e: if e.errno != errno.ENOENT: raise @@ -506,7 +509,7 @@ def isdir(path): try: st = os.stat(path) return stat.S_ISDIR(st.st_mode) - except OSError, inst: + except OSError as inst: if inst.errno == errno.EIO: raise CommandException(errno.EIO, "os.stat(%s)" % path, "failed") return False @@ -531,7 +534,7 @@ def ismount(path): try: s1 = os.stat(path) s2 = os.stat(os.path.join(path, '..')) - except OSError, inst: + except OSError as inst: raise CommandException(inst.errno, "os.stat") dev1 = s1.st_dev dev2 = s2.st_dev @@ -543,7 +546,7 @@ def ismount(path): return True # path/.. is the same i-node as path return False -def makedirs(name, mode=0777): +def makedirs(name, mode=0o777): head, tail = os.path.split(name) if not tail: head, tail = os.path.split(head) @@ -740,13 +743,13 @@ def find_my_pbd_record(session, host_ref, sr_ref): if pbds[pbd_ref]['host'] == host_ref and pbds[pbd_ref]['SR'] == sr_ref: return [pbd_ref,pbds[pbd_ref]] return None - except Exception, e: + except Exception as e: SMlog("Caught exception while looking up PBD for host %s SR %s: %s" % (str(host_ref), str(sr_ref), str(e))) return None def find_my_pbd(session, host_ref, sr_ref): ret = find_my_pbd_record(session, host_ref, sr_ref) - if ret <> None: + if ret != None: return ret[0] else: return None @@ -766,7 +769,7 @@ def test_hostPBD_devs(session, sr_uuid, devs): break if record["host"] == host: devconfig = record["device_config"] - if devconfig.has_key('device'): + if 'device' in devconfig: for device in devconfig['device'].split(','): if os.path.realpath(device) == os.path.realpath(dev): return True; @@ -782,7 +785,7 @@ def test_hostPBD_lun(session, targetIQN, LUNid): record = pbds[pbd] if record["host"] == host: devconfig = record["device_config"] - if devconfig.has_key('targetIQN') and devconfig.has_key('LUNid'): + if 'targetIQN' in devconfig and 'LUNid' in devconfig: if devconfig['targetIQN'] == targetIQN and \ devconfig['LUNid'] == LUNid: return True; @@ -804,11 +807,11 @@ def test_SCSIid(session, sr_uuid, SCSIid): break devconfig = record["device_config"] sm_config = session.xenapi.SR.get_sm_config(record["SR"]) - if devconfig.has_key('SCSIid') and devconfig['SCSIid'] == SCSIid: + if 'SCSIid' in devconfig and devconfig['SCSIid'] == SCSIid: return True; - elif sm_config.has_key('SCSIid') and sm_config['SCSIid'] == SCSIid: + elif 'SCSIid' in sm_config and sm_config['SCSIid'] == SCSIid: return True; - elif sm_config.has_key('scsi-' + SCSIid): + elif 'scsi-' + SCSIid in sm_config: return True; return False @@ -895,7 +898,7 @@ def test_activePoolPBDs(session, host, uuid): def remove_mpathcount_field(session, host_ref, sr_ref, SCSIid): try: pbdref = find_my_pbd(session, host_ref, sr_ref) - if pbdref <> None: + if pbdref != None: key = "mpath-" + SCSIid session.xenapi.PBD.remove_from_other_config(pbdref, key) except: @@ -919,7 +922,7 @@ def _testHost(hostname, port, errstring): # Fix for MS storage server bug sock.send('\n') sock.close() - except socket.error, reason: + except socket.error as reason: SMlog("_testHost: Connect failed after %d seconds (%s) - %s" \ % (timeout, hostname, reason)) raise xs_errors.XenError(errstring) @@ -962,7 +965,7 @@ def test_scsiserial(session, device): for SR in SRs: record = SRs[SR] conf = record["sm_config"] - if conf.has_key('devserial'): + if 'devserial' in conf: for dev in conf['devserial'].split(','): if _isSCSIid(dev): if match_scsiID(dev, scsiID): @@ -1084,7 +1087,7 @@ def _containsVDIinuse(srobj): if not vdi['managed']: continue sm_config = vdi['sm_config'] - if sm_config.has_key('SRRef'): + if 'SRRef' in sm_config: try: PBDs = srobj.session.xenapi.SR.get_PBDs(sm_config['SRRef']) for pbd in PBDs: @@ -1109,16 +1112,16 @@ def isVDICommand(cmd): def p_id_fork(): try: p_id = os.fork() - except OSError, e: - print "Fork failed: %s (%d)" % (e.strerror,e.errno) + except OSError as e: + print("Fork failed: %s (%d)" % (e.strerror,e.errno)) sys.exit(-1) if (p_id == 0): os.setsid() try: p_id = os.fork() - except OSError, e: - print "Fork failed: %s (%d)" % (e.strerror,e.errno) + except OSError as e: + print("Fork failed: %s (%d)" % (e.strerror,e.errno)) sys.exit(-1) if (p_id == 0): os.chdir('/opt/xensource/sm') @@ -1333,7 +1336,7 @@ def findRunningProcessOrOpenFile(name, process = True): # Just want the process name argv = prog.split('\x00') prog = argv[0] - except IOError, e: + except IOError as e: if e.errno in (errno.ENOENT, errno.ESRCH): SMlog("ERROR %s reading %s, ignore" % (e.errno, pid)) continue @@ -1344,7 +1347,7 @@ def findRunningProcessOrOpenFile(name, process = True): try: fd_dir = os.path.join('/proc', pid, 'fd') files = os.listdir(fd_dir) - except OSError, e: + except OSError as e: if e.errno in (errno.ENOENT, errno.ESRCH): SMlog("ERROR %s reading fds for %s, ignore" % (e.errno, pid)) # Ignore pid that are no longer valid @@ -1367,7 +1370,7 @@ def findRunningProcessOrOpenFile(name, process = True): SMlog("File %s has an open handle with process %s " "with pid %s" % (name, prog, pid)) processandpids.append((prog, pid)) - except Exception, e: + except Exception as e: SMlog("Exception checking running process or open file handles. "\ "Error: %s" % str(e)) retVal = False @@ -1382,7 +1385,7 @@ def retry(f, maxretry=20, period=3): while True: try: return f() - except Exception, e: + except Exception as e: SMlog("Got exception: %s. Retry number: %s" % (str(e),retries)) retries += 1 @@ -1462,7 +1465,7 @@ def __init__(self, filename): cmd, shell=True, \ stdin=subprocess.PIPE, stdout=subprocess.PIPE, \ stderr=subprocess.PIPE, close_fds=True) - except Exception, e: + except Exception as e: SMlog("Error: %s. Uncompress failed for %s" % (str(e), filename)) raise Exception(str(e)) @@ -1545,7 +1548,7 @@ def getTuple(self): if round_off != 0: zeros = self.spawn_p.stdout.read( extractXVA.BLOCK_SIZE - round_off) - except Exception, e: + except Exception as e: SMlog("Error: %s. File set extraction failed %s" % (str(e), \ self.__filename)) @@ -1769,7 +1772,7 @@ def read_caching_is_restricted(session): return False def sessions_less_than_targets(other_config, device_config): - if device_config.has_key('multihomelist') and other_config.has_key('iscsi_sessions'): + if 'multihomelist' in device_config and 'iscsi_sessions' in other_config: sessions = int(other_config['iscsi_sessions']) targets = len(device_config['multihomelist'].split(',')) SMlog("Targets %d and iscsi_sessions %d" %(targets, sessions)) diff --git a/drivers/verifyVHDsOnSR.py b/drivers/verifyVHDsOnSR.py index f6c6587e6..8e962ce8b 100755 --- a/drivers/verifyVHDsOnSR.py +++ b/drivers/verifyVHDsOnSR.py @@ -20,6 +20,7 @@ # on a VHD based SR. (FC or iSCSI) # +from __future__ import print_function import os import sys import util @@ -72,7 +73,7 @@ def activateVdi(sr_uuid, vdi_uuid, vhd_path): if count == 1: try: lvutil.activateNoRefcount(vhd_path, False) - except Exception, e: + except Exception as e: util.SMlog(" lv activate failed for %s with error %s" % (vhd_path, str(e))) RefCounter.put(vdi_uuid, True, name_space) @@ -92,7 +93,7 @@ def deactivateVdi(sr_uuid, vdi_uuid, vhd_path): return try: lvutil.deactivateNoRefcount(vhd_path) - except Exception, e: + except Exception as e: util.SMlog(" lv de-activate failed for %s with error %s" % (vhd_path, str(e))) RefCounter.get(vdi_uuid, False, name_space) diff --git a/drivers/vhdutil.py b/drivers/vhdutil.py index 422834eb8..5c3711895 100755 --- a/drivers/vhdutil.py +++ b/drivers/vhdutil.py @@ -144,7 +144,7 @@ def getAllVHDs(pattern, extractUuidFunction, vgName = None, \ cmd.append("-a") try: ret = ioretry(cmd) - except Exception, e: + except Exception as e: util.SMlog("WARN: vhd scan failed: output: %s" % e) ret = ioretry(cmd + ["-c"]) util.SMlog("WARN: vhd scan with NOFAIL flag, output: %s" % ret) diff --git a/drivers/wwid_conf.py b/drivers/wwid_conf.py index a343c6dee..57a23f8ab 100755 --- a/drivers/wwid_conf.py +++ b/drivers/wwid_conf.py @@ -19,6 +19,7 @@ # +from __future__ import print_function import fileinput, shutil, sys, re import util, lock @@ -56,12 +57,12 @@ def edit_wwid(wwid, remove=False): add_mode = True for line in fileinput.input(tmp_file, inplace=1): if add_mode: - print line, + print(line, end=' ') else: if wwid_regex.match(line): add_mode = True else: - print line, + print(line, end=' ') continue if filt_regex.match(line): @@ -70,7 +71,7 @@ def edit_wwid(wwid, remove=False): add_mode = False continue else: - print "\twwid \"%s\""%wwid + print("\twwid \"%s\""%wwid) shutil.move(tmp_file, CONF_FILE) @@ -123,13 +124,13 @@ def check_conf_file(): def usage(): - print "Usage: %s [-r] -d -w " % sys.argv[0] - print "Usage: %s -f [-r] -w " % sys.argv[0] - print "\tAdd a device wwid to multipath.conf whitelist" - print "\t-r: remove" - print "\t-f: if provided the operation will be performed anyway" - print "\t otherwise it will be after checking is" - print "\t blacklisted (or not)" + print("Usage: %s [-r] -d -w " % sys.argv[0]) + print("Usage: %s -f [-r] -w " % sys.argv[0]) + print("\tAdd a device wwid to multipath.conf whitelist") + print("\t-r: remove") + print("\t-f: if provided the operation will be performed anyway") + print("\t otherwise it will be after checking is") + print("\t blacklisted (or not)") if __name__ == "__main__": diff --git a/drivers/xs_errors.py b/drivers/xs_errors.py index 795d194e7..5c2ac2058 100644 --- a/drivers/xs_errors.py +++ b/drivers/xs_errors.py @@ -42,7 +42,7 @@ def __new__(self, key, opterr=None): ########END####### # Now find the specific error - if errorlist.has_key(key): + if key in errorlist: subdict = errorlist[key] errorcode = int(subdict['value']) errormessage = subdict['description'] diff --git a/test_support/faultinjection/FileSR.py b/test_support/faultinjection/FileSR.py index 9b22e4da8..1ba9048a7 100755 --- a/test_support/faultinjection/FileSR.py +++ b/test_support/faultinjection/FileSR.py @@ -8,6 +8,7 @@ # # FileSR: local-file storage repository +from __future__ import print_function import SR, VDI, SRCommand, util import statvfs import os, re @@ -44,7 +45,7 @@ def handles(srtype): def load(self, sr_uuid): self.sr_vditype = SR.DEFAULT_TAP - if not self.dconf.has_key('location') or not self.dconf['location']: + if 'location' not in self.dconf or not self.dconf['location']: raise xs_errors.XenError('ConfigLocationMissing') self.path = self.dconf['location'] self.attached = False @@ -61,7 +62,7 @@ def create(self, sr_uuid, size): else: try: util.ioretry(lambda: os.mkdir(self.path)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code == errno.EEXIST: raise xs_errors.XenError('SRExists') else: @@ -93,13 +94,13 @@ def delete(self, sr_uuid): fullpath = os.path.join(self.path,name) try: util.ioretry(lambda: os.unlink(fullpath)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.ENOENT and \ inst.code != errno.EISDIR: raise xs_errors.XenError('FileSRDelete', \ opterr='failed to remove %s error %d' \ % (fullpath, inst.code)) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('FileSRDelete', \ opterr='error %d' % inst.code) @@ -158,7 +159,7 @@ def _checkpath(self, path): if util.ioretry(lambda: util.isdir(path)): return True return False - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('EIO', \ opterr='IO error checking path %s' % path) @@ -175,16 +176,16 @@ def _loadvdis(self): try: self.vdis[uuid] = self.vdi(uuid) self.vdis[uuid].marked_deleted = self.vdis[uuid].hidden - except SR.SRException, inst: + except SR.SRException as inst: pass # Mark parent VDIs as Read-only and generate virtual allocation self.virtual_allocation = 0 for uuid, vdi in self.vdis.iteritems(): if vdi.parent: - if self.vdis.has_key(vdi.parent): + if vdi.parent in self.vdis: self.vdis[vdi.parent].read_only = True - if geneology.has_key(vdi.parent): + if vdi.parent in geneology: geneology[vdi.parent].append(uuid) else: geneology[vdi.parent] = [uuid] @@ -196,7 +197,7 @@ def _cleanup_leafnodes(self): # - nodes which have no children # - nodes marked hidden for uuid, vdi in self.vdis.iteritems(): - if not geneology.has_key(uuid) and vdi.hidden: + if uuid not in geneology and vdi.hidden: self._delete_parents(uuid) def _delete_parents(self, child): @@ -213,7 +214,7 @@ def _delete_parents(self, child): (child,self.vdis[child].vdi_type)) try: util.ioretry(lambda: os.unlink(child_path)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.ENOENT: raise xs_errors.XenError('VDIRemove', \ opterr='failed to remove VDI %s error %d' % \ @@ -253,7 +254,7 @@ def _replay(self, logentry): args.append(item) ret = cmd(*args) if ret: - print ret + print(ret) def _compare_args(self, a, b): try: @@ -296,7 +297,7 @@ def load(self, vdi_uuid): try: st = util.ioretry(lambda: os.stat(self.path)) self.utilisation = long(st.st_size) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code == errno.EIO: raise xs_errors.XenError('VDILoad', \ opterr='Failed load VDI information %s' % self.path) @@ -306,13 +307,13 @@ def load(self, vdi_uuid): try: diskinfo = util.ioretry(lambda: self._query_info(self.path)) - if diskinfo.has_key('parent'): + if 'parent' in diskinfo: self.parent = diskinfo['parent'] else: self.parent = '' self.size = long(diskinfo['size']) * 1024 * 1024 self.hidden = long(diskinfo['hidden']) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('VDILoad', \ opterr='Failed load VDI information %s' % self.path) @@ -336,7 +337,7 @@ def create(self, sr_uuid, vdi_uuid, size): assert((size_mb + (metasize/(1024*1024))) < MAX_DISK_MB) util.ioretry(lambda: self._create(str(size_mb), self.path)) self.size = util.ioretry(lambda: self._query_v(self.path)) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('VDICreate', opterr='error %d' % inst.code) except AssertionError: raise xs_errors.XenError('VDISize') @@ -356,7 +357,7 @@ def delete(self, sr_uuid, vdi_uuid): try: util.ioretry(lambda: self._mark_hidden(self.path)) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('VDIDelete', opterr='error %d' % inst.code) def attach(self, sr_uuid, vdi_uuid): @@ -366,7 +367,7 @@ def attach(self, sr_uuid, vdi_uuid): try: self.attached = True return super(FileVDI, self).attach(sr_uuid, vdi_uuid) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('VDILoad', opterr='error %d' % inst.code) def detach(self, sr_uuid, vdi_uuid): @@ -405,7 +406,7 @@ def clone(self, sr_uuid, vdi_uuid, dest): try: try: util.ioretry(lambda: os.rename(src,newsrc)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.ENOENT: self._clonecleanup(src,dst,newsrc) util.end_log_entry(self.sr.path, self.path, ["error"]) @@ -416,7 +417,7 @@ def clone(self, sr_uuid, vdi_uuid, dest): # mark the original file (in this case, its newsrc) # as hidden so that it does not show up in subsequent scans util.ioretry(lambda: self._mark_hidden(newsrc)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.EIO: self._clonecleanup(src,dst,newsrc) util.end_log_entry(self.sr.path, self.path, ["error"]) @@ -431,7 +432,7 @@ def clone(self, sr_uuid, vdi_uuid, dest): except: pass - except util.CommandException, inst: + except util.CommandException as inst: self._clonecleanup(src,dst,newsrc) util.end_log_entry(self.sr.path, self.path, ["error"]) raise xs_errors.XenError('VDIClone', @@ -468,7 +469,7 @@ def snapshot(self, sr_uuid, vdi_uuid, dest): try: try: util.ioretry(lambda: os.rename(src,dst)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.ENOENT: self._snapcleanup(src,dst) util.end_log_entry(self.sr.path, self.path, ["error"]) @@ -476,7 +477,7 @@ def snapshot(self, sr_uuid, vdi_uuid, dest): util.ioretry(lambda: self._singlesnap(src, dst)) - except util.CommandException, inst: + except util.CommandException as inst: self._snapcleanup(src,dst) util.end_log_entry(self.sr.path, self.path, ["error"]) raise xs_errors.XenError('VDISnapshot', @@ -508,25 +509,25 @@ def _singlesnap(self, src, dst): def _clonecleanup(self,src,dst,newsrc): try: util.ioretry(lambda: os.unlink(src)) - except util.CommandException, inst: + except util.CommandException as inst: pass try: util.ioretry(lambda: os.unlink(dst)) - except util.CommandException, inst: + except util.CommandException as inst: pass try: util.ioretry(lambda: os.rename(newsrc,src)) - except util.CommandException, inst: + except util.CommandException as inst: pass def _snapcleanup(self,src,dst): try: util.ioretry(lambda: os.unlink(dst)) - except util.CommandException, inst: + except util.CommandException as inst: pass try: util.ioretry(lambda: os.rename(src,dst)) - except util.CommandException, inst: + except util.CommandException as inst: pass def _checkpath(self, path): @@ -534,7 +535,7 @@ def _checkpath(self, path): if not util.ioretry(lambda: util.pathexists(path)): return False return True - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('EIO', \ opterr='IO error checking path %s' % path) diff --git a/test_support/faultinjection/NFSSR.py b/test_support/faultinjection/NFSSR.py index 1c923d392..a04ba1326 100755 --- a/test_support/faultinjection/NFSSR.py +++ b/test_support/faultinjection/NFSSR.py @@ -63,9 +63,9 @@ def handles(type): def load(self, sr_uuid): self.sr_vditype = SR.DEFAULT_TAP - if not self.dconf.has_key('serverpath'): + if 'serverpath' not in self.dconf: raise xs_errors.XenError('ConfigServerPathMissing') - if not self.dconf.has_key('server'): + if 'server' not in self.dconf: raise xs_errors.XenError('ConfigServerMissing') if not self._isvalidpathstring(self.dconf['serverpath']): raise xs_errors.XenError('ConfigServerPathBad', \ @@ -83,7 +83,7 @@ def attach(self, sr_uuid): util.ioretry(lambda: util.pread(["/usr/sbin/rpcinfo","-t", \ "%s" % self.remoteserver, "nfs","3"]), \ errlist=[errno.EPERM], nofail=1) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('NFSVersion', \ opterr='or NFS server timed out') try: @@ -98,7 +98,7 @@ def attach(self, sr_uuid): "udp,soft,timeo=%d,retrans=1,noac" % \ timeout]), errlist=[errno.EPIPE, errno.EIO], nofail=1) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('NFSMount') return super(NFSSR, self).attach(sr_uuid) @@ -108,10 +108,10 @@ def detach(self, sr_uuid): try: util.pread(["umount", self.path]) os.rmdir(self.path) - except util.CommandException, inst: + except util.CommandException as inst: raise xs_errors.XenError('NFSUnMount', \ opterr='error is %d' % inst.code) - except OSError, inst: + except OSError as inst: raise xs_errors.XenError('NFSUnMount', \ opterr='directory removal error is %d' % inst.sterror) return super(NFSSR, self).detach(sr_uuid) @@ -139,7 +139,7 @@ def create(self, sr_uuid, size): else: try: util.ioretry(lambda: util.makedirs(newpath)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.EEXIST: self.detach(sr_uuid) raise xs_errors.XenError('NFSCreate', \ @@ -163,7 +163,7 @@ def delete(self, sr_uuid): if util.ioretry(lambda: util.pathexists(newpath)): util.ioretry(lambda: os.rmdir(newpath)) self.detach(sr_uuid) - except util.CommandException, inst: + except util.CommandException as inst: self.detach(sr_uuid) if inst.code != errno.ENOENT: raise xs_errors.XenError('NFSDelete') @@ -238,7 +238,7 @@ def unlock(self, sr_uuid, vdi_uuid, l_uuid): try: cmd = [SR.LOCK_UTIL, "unlock", self.path, "w", l_uuid] self.status = util.ioretry(lambda: util.pread2(cmd)) - except util.CommandException, inst: + except util.CommandException as inst: if inst.code != errno.ENOENT: raise xs_errors.XenError('VDIInUse', \ opterr='Unable to release lock') diff --git a/test_support/faultinjection/util.py b/test_support/faultinjection/util.py index 8131a5c24..6aa299db6 100644 --- a/test_support/faultinjection/util.py +++ b/test_support/faultinjection/util.py @@ -92,7 +92,7 @@ def listdir(path): cmd = ["ls", path, "-1", "--color=never"] try: text = pread2(cmd).split('\n') - except CommandException, inst: + except CommandException as inst: if inst.code == errno.ENOENT: raise CommandException(errno.EIO) else: @@ -182,7 +182,7 @@ def ioretry(f, errlist=[errno.EIO], maxretry=IORETRY_MAX, \ syslog.syslog("FITrace: ioretry reset: ALLOW all packets") time.sleep(iosleep) return value - except OSError, inst: + except OSError as inst: for etest in errlist: if int(inst.errno) == etest: retries += 1 @@ -204,7 +204,7 @@ def ioretry(f, errlist=[errno.EIO], maxretry=IORETRY_MAX, \ syslog.syslog("FITrace: ioretry reset: ALLOW all packets") time.sleep(iosleep) raise CommandException(inst.errno) - except CommandException, inst: + except CommandException as inst: for etest in errlist: if int(inst.code) == etest: retries += 1 @@ -312,7 +312,7 @@ def pathexists(path): try: os.stat(path) return True - except OSError, inst: + except OSError as inst: if inst.errno == errno.EIO: raise CommandException(errno.EIO) return False @@ -321,7 +321,7 @@ def isdir(path): try: st = os.stat(path) return stat.S_ISDIR(st.st_mode) - except OSError, inst: + except OSError as inst: if inst.errno == errno.EIO: raise CommandException(errno.EIO) return False @@ -331,7 +331,7 @@ def ismount(path): try: s1 = os.stat(path) s2 = os.stat(os.path.join(path, '..')) - except OSError, inst: + except OSError as inst: if inst.errno == errno.EIO: raise CommandException(errno.EIO) dev1 = s1.st_dev @@ -344,7 +344,7 @@ def ismount(path): return True # path/.. is the same i-node as path return False -def makedirs(name, mode=0777): +def makedirs(name, mode=0o777): head, tail = os.path.split(name) if not tail: head, tail = os.path.split(head) diff --git a/test_support/lvhd_test/snapshot_stress.py b/test_support/lvhd_test/snapshot_stress.py index fba435ef4..b17f4c3ba 100755 --- a/test_support/lvhd_test/snapshot_stress.py +++ b/test_support/lvhd_test/snapshot_stress.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function import sys import random import pickle @@ -203,9 +204,9 @@ def randomProgram(self, num_actions): def execute(self, action, context): # execute action - print >> sys.stderr, context.i, action, + print(context.i, action, end=' ', file=sys.stderr) action.execute(context) - print >> sys.stderr, "# %d" % context.nodeCount() + print("# %d" % context.nodeCount(), file=sys.stderr) # perform self checks, if available self.check(action) @@ -261,9 +262,9 @@ def load(self, path): PATH = "/tmp/snapshot" def usage(): - print "Usage:" - print "%s gen " % sys.argv[0] - print "%s rerun " % sys.argv[0] + print("Usage:") + print("%s gen " % sys.argv[0]) + print("%s rerun " % sys.argv[0]) def xe(cmd, *args): argv = [ "/opt/xensource/bin/xe", cmd ] diff --git a/test_support/lvhd_test/storagemanager.py b/test_support/lvhd_test/storagemanager.py index a9c730e2e..a774b7e0b 100644 --- a/test_support/lvhd_test/storagemanager.py +++ b/test_support/lvhd_test/storagemanager.py @@ -440,7 +440,7 @@ def onMaster(self, plugin, fn, args): return self._onMaster(plugin, fn, args) def _getVBDLetter(self, vbd): - if self.usedVBDLetters.has_key(vbd): + if vbd in self.usedVBDLetters: return self.usedVBDLetters[vbd] else: return None @@ -701,7 +701,7 @@ def _cloneVDI(self, vdi): try: stdout = tutil.execCmd(cmd, 0, self.logger, LOG_LEVEL_CMD) break - except tutil.CommandException, inst: + except tutil.CommandException as inst: if str(inst).find("VDI_IN_USE") != -1: self.logger.log("Command failed, retrying", LOG_LEVEL_CMD) time.sleep(CMD_RETRY_PERIOD) @@ -723,7 +723,7 @@ def _snapshotVDI(self, vdi, single = None): try: stdout = tutil.execCmd(cmd, 0, self.logger, LOG_LEVEL_CMD) break - except tutil.CommandException, inst: + except tutil.CommandException as inst: if str(inst).find("VDI_IN_USE") != -1: self.logger.log("Command failed, retrying", LOG_LEVEL_CMD) time.sleep(CMD_RETRY_PERIOD) @@ -787,7 +787,7 @@ def _unplugVBD(self, vbd): cmd = "xe vbd-unplug uuid=%s" % vbd try: tutil.execCmd(cmd, 0, self.logger, LOG_LEVEL_CMD) - except tutil.CommandException, inst: + except tutil.CommandException as inst: if str(inst).find("device is not currently attached") == -1: raise diff --git a/test_support/lvhd_test/test_content_id.py b/test_support/lvhd_test/test_content_id.py index 721bf38f2..b053979c7 100755 --- a/test_support/lvhd_test/test_content_id.py +++ b/test_support/lvhd_test/test_content_id.py @@ -1,4 +1,5 @@ #!/usr/bin/python +from __future__ import print_function import unittest import logger import tutil @@ -65,7 +66,7 @@ def tearDown(self): # FIXME check args if len(sys.argv) < 3: - print 'usage: ' + sys.argv[0] + ' ' + print('usage: ' + sys.argv[0] + ' ') sys.exit(os.EX_USAGE) sr_uuid = sys.argv[1] diff --git a/test_support/lvhd_test/test_intellicache.py b/test_support/lvhd_test/test_intellicache.py index e77637ab5..2d95fb338 100755 --- a/test_support/lvhd_test/test_intellicache.py +++ b/test_support/lvhd_test/test_intellicache.py @@ -17,6 +17,7 @@ # # TODO Once this script is tested, it should become a unit test. +from __future__ import print_function import random import storagemanager import string @@ -82,7 +83,7 @@ def main(argv): elif '-v' == fields[0] or '--verbose' == fields[0]: verbose = True else: - print 'invalid key \'' + fields[0] + '\'' + print('invalid key \'' + fields[0] + '\'') return 2 logger.logger = tutil.Logger('/tmp/test_intellicache.log', 2) @@ -91,12 +92,12 @@ def main(argv): if None == vm_uuid: # If no VM has been specified, pick any one. # TODO not implemented - print 'no VM specified' + print('no VM specified') return os.EX_CONFIG if None == sr_uuid: # If no SR has been specified, pick one that has caching enabled. - print 'no SR specified' + print('no SR specified') # TODO not implemented return os.EX_CONFIG @@ -112,7 +113,7 @@ def main(argv): # acts as a cache. local_cache_sr = sm._host_get_local_cache_sr() if not tutil.validateUUID(local_cache_sr): - print 'caching not enabled' + print('caching not enabled') sys.exit(os.EX_CONFIG) # FIXME other power states not taken into account @@ -129,7 +130,7 @@ def main(argv): vdi_uuid = sm._createVDI(sr_uuid, size_gb * (2**30)) if verbose: - print 'test VDI is ' + vdi_uuid + print('test VDI is ' + vdi_uuid) # The original VHD file that backs the VDI on the NFS SR. vdi_file = '/var/run/sr-mount/' + sr_uuid + '/' + vdi_uuid + '.vhd' @@ -187,11 +188,11 @@ def main(argv): assert not os.path.exists(cache_file) if verbose: - print 'cache ' + str(cache_on), + print('cache ' + str(cache_on), end=' ') if cache_on: - print ', persistent ' + str(persistent) + print(', persistent ' + str(persistent)) else: - print + print() # If the VM was restarted, it's IP address may have changed. if True == vm_shutdown: @@ -249,15 +250,15 @@ def main(argv): if persistent: # Persistent cache mode: ensure the original VDI has grown. if new_size < vdi_file_prev_size: - print 'new VDI file size (' + str(new_size) \ + print('new VDI file size (' + str(new_size) \ + ') should be bigger than old one (' \ - + str(vdi_file_prev_size) + ')' + + str(vdi_file_prev_size) + ')') assert False else: # Reset cache mode: no writes should reach the VDI on the # NFS SR if not new_size == vdi_file_prev_size: - print 'VDI on the shared SR has been modified whilst in reset mode, old size ' + str(vdi_file_prev_size) + ', new size ' + str(new_size) + print('VDI on the shared SR has been modified whilst in reset mode, old size ' + str(vdi_file_prev_size) + ', new size ' + str(new_size)) sm._unplugVBD(vbd_uuid) @@ -274,9 +275,9 @@ def main(argv): sm._destroyVDI(vdi_snapshot_uuid) sm._destroyVDI(vdi_uuid) - print 'total ' + str(stats_total) + ', cached ' + str(stats_cached) \ + print('total ' + str(stats_total) + ', cached ' + str(stats_cached) \ + ', plug/unplug loops ' + str(stats_plug_unplug_loops) + \ - ', persistent ' + str(stats_persistent) + ', persistent ' + str(stats_persistent)) return 0 if __name__ == '__main__': diff --git a/test_support/lvhd_test/testsm.py b/test_support/lvhd_test/testsm.py index 2c9ba6d78..990e12fc8 100755 --- a/test_support/lvhd_test/testsm.py +++ b/test_support/lvhd_test/testsm.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function import re import os import sys @@ -10,6 +11,7 @@ import tutil import storagemanager +from functools import reduce sys.path.append("/opt/xensource/sm") from ipc import IPCFlag @@ -1702,7 +1704,7 @@ def _doAttachDetachLoop(sr, vdi, numIters): logger.log("Iteration %d" % i) _testAttachVDI(vdi, False) _testDetachVDI(vdi) - except Exception, e: + except Exception as e: logger.log("Failed: %s" % e) open("%s/%s%d" % (WORKER_DIR, WORKER_FAIL_FILE, os.getpid()), 'w').close() return @@ -1718,7 +1720,7 @@ def _doSnapshotDestroyLoop(sr, vdi, numIters): logger.log("Iteration %d" % i) vdiSnap = _testSnapshotVDI(sr, vdi, False) sm.destroyVDI(vdiSnap) - except Exception, e: + except Exception as e: logger.log("Failed: %s" % e) open("%s/%s%d" % (WORKER_DIR, WORKER_FAIL_FILE, os.getpid()), 'w').close() return @@ -1748,7 +1750,7 @@ def _killAll(pids): try: os.killpg(pid, signal.SIGKILL) logger.log("Killed PID %d" % pid) - except Exception, e: + except Exception as e: logger.log("Error killing PID %d: %s" % (pid, e)) def _getStatus(pid): @@ -1788,7 +1790,7 @@ def _testPause(sr, numVDIs, numIters): pids.append(pid) pid = _createWorker(sr, WORKER_TYPE_SNAPSHOT_DESTROY, vdis[i], numIters, chr(ord('a') + i)) pids.append(pid) - except Exception, e: + except Exception as e: logger.log("Exception: %s, aborting workers" % e) open("%s/%s" % (WORKER_DIR, WORKER_ABORT_FILE), 'w').close() success = False @@ -2027,12 +2029,12 @@ def runJournalTests(sr): _testJournalResize(sr, initSize, newSize, fistPoint) def usage(): - print "Params: -t lvhd|lvm|ext|nfs -m basic|extended|coalesce|jvhd " \ + print("Params: -t lvhd|lvm|ext|nfs -m basic|extended|coalesce|jvhd " \ "[-v 1..4 log verbosity (default 3)] " \ "[-a NUM skip to test NUM] [-b NUM stop after test NUM] " \ - "[-h print this help]" - print - print "The modes are: \n" \ + "[-h print this help]") + print() + print("The modes are: \n" \ " - basic: tests SR attach,detach,probe; " \ "VDI create,snapshot,resize (LVHD only)\n"\ " - pause: tests concurrent attach/detach and snapshot/delete\n" \ @@ -2040,12 +2042,12 @@ def usage(): "add more parameter values (LVHD only)\n" \ " - coalesce: test coalescing\n" \ " - caching: test local caching\n" \ - " - jvhd: test VHD journaling (LVHD only)\n" - print - print "The script expects an empty SR of the specified type to be " \ + " - jvhd: test VHD journaling (LVHD only)\n") + print() + print("The script expects an empty SR of the specified type to be " \ "available (if there are multiple SRs of the specified type, the " \ "default SR is used if it is the right type). " \ - "No cleanup is performed upon a failure to assist debugging." + "No cleanup is performed upon a failure to assist debugging.") sys.exit(0) def main(): @@ -2096,7 +2098,7 @@ def main(): usage() logger = tutil.Logger(LOG_FILE, verbosity) - print "Log file in %s" % LOG_FILE + print("Log file in %s" % LOG_FILE) logger.log("Testing: %s" % testMode, 0) if skipTo: logger.log("Skipping to test %d" % skipTo, 0) @@ -2172,7 +2174,7 @@ def main(): logger.log("Description: %s" % info[1], 0) logger.log("Stack trace:\n%s" % tb, 0) success = False - except StopRequest, e: + except StopRequest as e: logger.log("Stop requested: %s" % e, 0) pass diff --git a/test_support/lvhd_test/tutil.py b/test_support/lvhd_test/tutil.py index 9d0757a05..70fedc822 100644 --- a/test_support/lvhd_test/tutil.py +++ b/test_support/lvhd_test/tutil.py @@ -1,3 +1,4 @@ +from __future__ import print_function # Various utility functions. # TODO why the leading "t" in the filename? @@ -50,7 +51,7 @@ def log(self, msg, verbosity = 1): (datetime.datetime.now(), indent, msg)) self._logfile.flush() if verbosity == 0: - print msg + print(msg) def write(self, msg): self._logfile.write("%s\n" % msg) @@ -182,12 +183,12 @@ def vm_get_ip(vm_uuid): (rc, stdout, stderr) = doexec(cmd) if 0 != rc: - print stdout + print(stdout) assert False # FIXME mo = re.search(ip_regex, stdout) if not mo: - print stdout + print(stdout) return None return mo.group() diff --git a/test_support/lvhd_test/vdi_tests.py b/test_support/lvhd_test/vdi_tests.py index 41a47d200..7b76cf2fc 100755 --- a/test_support/lvhd_test/vdi_tests.py +++ b/test_support/lvhd_test/vdi_tests.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function import random import storagemanager import string @@ -127,7 +128,7 @@ def tearDown(self): # FIXME check args if len(sys.argv) < 3: - print 'usage: ' + sys.argv[0] + ' ' + print('usage: ' + sys.argv[0] + ' ') sys.exit(os.EX_USAGE) sr_uuid = sys.argv[1] diff --git a/test_support/parallelise_stress_tests.py b/test_support/parallelise_stress_tests.py index 2b0cddfa7..a2aee5661 100755 --- a/test_support/parallelise_stress_tests.py +++ b/test_support/parallelise_stress_tests.py @@ -1,5 +1,6 @@ #!/usr/bin/python +from __future__ import print_function import sys, os, datetime, time def shellquote(arg): @@ -12,14 +13,14 @@ def pread(cmdlist): t = datetime.datetime.now() LOGBASE = "/tmp/SR-testlog-%d" % time.mktime(t.timetuple()) -print "FILE: [%s]" % LOGBASE +print("FILE: [%s]" % LOGBASE) script_args = sys.argv script_args[0] = './test_stress_fs.sh' -print "Calling args: [%s]" % script_args +print("Calling args: [%s]" % script_args) for i in range(0,2): LOGFILE="%s-%d" % (LOGBASE, i) - print "\tCalling stress_test (%d), logfile %s" % (i, LOGFILE) + print("\tCalling stress_test (%d), logfile %s" % (i, LOGFILE)) script_args.append("DEBUG_FILE=%s" % LOGFILE) pread(script_args) time.sleep(20) diff --git a/test_support/sshutil_test.py b/test_support/sshutil_test.py index b0cfd7d82..b7151894c 100755 --- a/test_support/sshutil_test.py +++ b/test_support/sshutil_test.py @@ -6,6 +6,7 @@ # trademarks of Citrix Systems, Inc. in the United States and/or other # countries. +from __future__ import print_function import sshutil import getpass import sys, os @@ -27,51 +28,51 @@ conn.connect() (rc, fw_supported, errlog, errmsg) = sshutil.check_version(conn) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: if not fw_supported : - print "FW version not supported" + print("FW version not supported") sys.exit() (rc, output, errlog, errmsg) = conn.command(command) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - for line in output: print line + for line in output: print(line) #Comment the next line to run the series of example test cases below. sys.exit() -print "\nListing SR volumes" +print("\nListing SR volumes") (rc, vol_list, errlog, errmsg) = sshutil.list_SR_vols(conn, "XenStorage") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print vol_list + print(vol_list) for id1 in range(len(vol_list)): - print "\nListing snapshots for volume:%s"% vol_list[id1] + print("\nListing snapshots for volume:%s"% vol_list[id1]) (rc, snap_list, errlog, errmsg) = sshutil.list_VDI_snaps(conn, vol_list[id1]) if (rc): - print errmsg + print(errmsg) for id2 in range(len(errlog)): - print errlog[id2] + print(errlog[id2]) else: - print snap_list + print(snap_list) for id3 in range(len(snap_list)): - print "\nListing snapshot connection details for %s"% snap_list[id3] + print("\nListing snapshot connection details for %s"% snap_list[id3]) (rc, output, errlog, errmsg) = sshutil.snap_conn_detail(conn, vol_list[id1], snap_list[id3]) if (rc): - print errmsg + print(errmsg) for id4 in range(len(errlog)): - print errlog[id4] + print(errlog[id4]) else: - print output + print(output) #sys.exit() #set the loop count below to run the tests repeatedly to create stress @@ -79,396 +80,396 @@ while True: if (loop_count == 0): break - print "\nListing all pools in the group" + print("\nListing all pools in the group") (rc, output, errlog, errmsg) = sshutil.all_StoragePools(conn) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) #sys.exit() - print "\nListing pool details for default pool" + print("\nListing pool details for default pool") (rc, output, errlog, errmsg) = sshutil.pool_detail(conn, "default") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) #sys.exit() - print "\nCreating accessvol in the SR" + print("\nCreating accessvol in the SR") (rc, output, iSCSIname, errlog, errmsg) = sshutil.vol_create(conn, "accessvol", "10GB", "thin", "cece3456-bad2-4fc2-9142-990d3d920fb7", "offline", 100, "volume-offline", "default") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output - print "iSCSI name: %s"% iSCSIname + print(output) + print("iSCSI name: %s"% iSCSIname) initiator_name = "iqn.2006-04.com.example:4567acdb" - print "\nCreating access control record for accessvol with initiator %s"% initiator_name + print("\nCreating access control record for accessvol with initiator %s"% initiator_name) (rc, output, errlog, errmsg) = sshutil.vol_create_access_rec_by_initiator(conn, "accessvol", initiator_name) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) initiator_name = "iqn.2006-04.com.example:4567acdb" - print "\nDeleting access information for initiator %s from accessvol"% initiator_name + print("\nDeleting access information for initiator %s from accessvol"% initiator_name) (rc, output, errlog, errmsg) = sshutil.vol_delete_access_rec_by_initiator(conn, "accessvol", initiator_name) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: for id in range(len(output)): - print output[id] + print(output[id]) #sys.exit() - print "\nDeleting accessvol from SR" + print("\nDeleting accessvol from SR") (rc, output, errlog, errmsg) = sshutil.vol_delete(conn, "accessvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) vdi_name = "XenStorage0ff867ef31210e7c5497f5c34916727d22267eb723c04479a063" - print "\nCreating VDI:%s in the SR" % vdi_name + print("\nCreating VDI:%s in the SR" % vdi_name) (rc, output, iSCSIname, errlog, errmsg) = sshutil.vol_create(conn, vdi_name, "10GB", "thin", "22267eb7-23c0-4479-a063-f5c34916727d", "offline", 100, "volume-offline", "default") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output - print "iSCSI name: %s"% iSCSIname + print(output) + print("iSCSI name: %s"% iSCSIname) - print "\nCreating snapshot of VDI:%s in the SR" % vdi_name + print("\nCreating snapshot of VDI:%s in the SR" % vdi_name) (rc, errlog, errmsg) = sshutil.vol_create_snapshot(conn, vdi_name, "bebe1234-bad2-4fc2-9142-990d3d920fb7", "eeff5678-bad2-4fc2-9142-990d3d92aaaa", "SNAPSHOT") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nListing snapshots of VDI: %s"% vdi_name + print("\nListing snapshots of VDI: %s"% vdi_name) (rc, snap_list, errlog, errmsg) = sshutil.list_VDI_snaps(conn, vdi_name) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print snap_list + print(snap_list) for id in range(len(snap_list)): - print "\nListing snapshot details for %s"% snap_list[id] + print("\nListing snapshot details for %s"% snap_list[id]) (rc, output, errlog, errmsg) = sshutil.snap_detail(conn, vdi_name, snap_list[id]) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) #sys.exit() snapname= "XenStorage" + "bebe1234-bad2-4fc2-9142-990d3d920fb7".replace("-", "") + "eeff5678-bad2-4fc2-9142-990d3d92aaaa".replace("-", "")[:20] - print "\nDeleting snapshot of VDI:%s from SR" % vdi_name + print("\nDeleting snapshot of VDI:%s from SR" % vdi_name) (rc, output, errlog, errmsg) = sshutil.snap_delete(conn, vdi_name, snapname) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nDeleting VDI:%s from SR" % vdi_name + print("\nDeleting VDI:%s from SR" % vdi_name) (rc, output, errlog, errmsg) = sshutil.vol_delete(conn, vdi_name) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nCreating bigvol in the SR" + print("\nCreating bigvol in the SR") (rc, output, iSCSIname, errlog, errmsg) = sshutil.vol_create(conn, "bigvol", "10GB", "thin", "bebe1234-bad2-4fc2-9142-990d3d920fb7", "offline", 100, "volume-offline", "default") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output - print "iSCSI name: %s"% iSCSIname + print(output) + print("iSCSI name: %s"% iSCSIname) - print "\nListing volume details for bigvol" + print("\nListing volume details for bigvol") (rc, output, errlog, errmsg) = sshutil.vol_detail(conn, "bigvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nBringing bigvol online" + print("\nBringing bigvol online") (rc, errlog, errmsg) = sshutil.vol_online(conn, "bigvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nShrinking bigvol to 8GB" + print("\nShrinking bigvol to 8GB") (rc, errlog, errmsg) = sshutil.vol_shrink(conn, "bigvol", "8GB") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nBringing bigvol offline" + print("\nBringing bigvol offline") (rc, errlog, errmsg) = sshutil.vol_offline(conn, "bigvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nShrinking bigvol to 8GB" + print("\nShrinking bigvol to 8GB") (rc, errlog, errmsg) = sshutil.vol_shrink(conn, "bigvol", "8GB") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nListing volume details for bigvol" + print("\nListing volume details for bigvol") (rc, output, errlog, errmsg) = sshutil.vol_detail(conn, "bigvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nBringing bigvol online" + print("\nBringing bigvol online") (rc, errlog, errmsg) = sshutil.vol_online(conn, "bigvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nGrowing bigvol to 12GB" + print("\nGrowing bigvol to 12GB") (rc, errlog, errmsg) = sshutil.vol_grow(conn, "bigvol", "12GB") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nListing volume details for bigvol" + print("\nListing volume details for bigvol") (rc, output, errlog, errmsg) = sshutil.vol_detail(conn, "bigvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) #sys.exit() - print "\nDeleting bigvol from SR" + print("\nDeleting bigvol from SR") (rc, output, errlog, errmsg) = sshutil.vol_delete(conn, "bigvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nBringing bigvol offline" + print("\nBringing bigvol offline") (rc, errlog, errmsg) = sshutil.vol_offline(conn, "bigvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nDeleting bigvol from SR" + print("\nDeleting bigvol from SR") (rc, output, errlog, errmsg) = sshutil.vol_delete(conn, "bigvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nListing SR volumes- Checking if myvol6 exists" + print("\nListing SR volumes- Checking if myvol6 exists") (rc, vol_list, errlog, errmsg) = sshutil.list_SR_vols(conn, "myvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print vol_list + print(vol_list) - print "\nCreating myvol6 in the SR" + print("\nCreating myvol6 in the SR") (rc, output, iSCSIname, errlog, errmsg) = sshutil.vol_create(conn, "myvol6", "5GB", "none", "bebe1234-bad2-4fc2-9142-990d3d920fb7", "offline", 100, "volume-offline", "default") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output - print "iSCSI name: %s"% iSCSIname + print(output) + print("iSCSI name: %s"% iSCSIname) - print "\nCreating clone of myvol6 in the SR" + print("\nCreating clone of myvol6 in the SR") (rc, output, iscsiname, errlog, errmsg) = sshutil.vol_create_clone(conn, "myvol6", "bebe1234-bad2-4fc2-9142-990d3d920fb7", "ddbb7698-bad2-4fc2-9142-990d3d920fb7", "UUID-ddbb7698-bad2-4fc2-9142-990d3d920fb7:DELETED-False") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output - print "iSCSI name: %s"% iSCSIname + print(output) + print("iSCSI name: %s"% iSCSIname) clone_name= "XenStorage" + "bebe1234-bad2-4fc2-9142-990d3d920fb7".replace("-", "") + "ddbb7698-bad2-4fc2-9142-990d3d920fb7".replace("-", "")[:20] - print "\nBringing clone %s online"% clone_name + print("\nBringing clone %s online"% clone_name) (rc, errlog, errmsg) = sshutil.vol_online(conn, clone_name) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nListing volume details for myvol6" + print("\nListing volume details for myvol6") (rc, output, errlog, errmsg) = sshutil.vol_detail(conn, "myvol6") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nListing SR volumes" + print("\nListing SR volumes") (rc, vol_list, errlog, errmsg) = sshutil.list_SR_vols(conn, "myvol") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print vol_list + print(vol_list) - print "\nBringing myvol6 online" + print("\nBringing myvol6 online") (rc, errlog, errmsg) = sshutil.vol_online(conn, "myvol6") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nBringing myvol6 offline" + print("\nBringing myvol6 offline") (rc, errlog, errmsg) = sshutil.vol_offline(conn, "myvol6") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nCreating access control record for myvol6" + print("\nCreating access control record for myvol6") (rc, output, errlog, errmsg) = sshutil.vol_create_access_rec_by_initiator(conn, "myvol6", "iqn.2008-04.com.example:12345a") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nBringing myvol6 online" + print("\nBringing myvol6 online") (rc, errlog, errmsg) = sshutil.vol_online(conn, "myvol6") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nCreating a snapshot of myvol6" + print("\nCreating a snapshot of myvol6") snapname= "XenStorage" + "bebe1234-bad2-4fc2-9142-990d3d920fb7".replace("-", "") + "ddbb5678-bad2-4fc2-9142-990d3d92aaaa".replace("-", "")[:20] (rc, errlog, errmsg) = sshutil.vol_create_snapshot(conn, "myvol6", "bebe1234-bad2-4fc2-9142-990d3d920fb7", "ddbb5678-bad2-4fc2-9142-990d3d92aaaa", "SNAPSHOT") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print "\nCreating a clone form snapshot %s of vol myvol6"% snapname + print("\nCreating a clone form snapshot %s of vol myvol6"% snapname) (rc, output, iscsiname, errlog, errmsg) = sshutil.vol_create_clone_from_snapshot(conn, "myvol6", snapname, "bebe1234-bad2-4fc2-9142-990d3d920fb7", "eeff9012-bad2-4fc2-9142-990d3d92cccc", "UUID-eeff9012-bad2-4fc2-9142-990d3d92cccc:DELETED-False") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output - print "iSCSI name of the clone is: %s"% iscsiname + print(output) + print("iSCSI name of the clone is: %s"% iscsiname) - print "\nListing snapshot details for %s"% snapname + print("\nListing snapshot details for %s"% snapname) (rc, output, errlog, errmsg) = sshutil.snap_detail(conn, "myvol6", snapname) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) clone_name= "XenStorage" + "bebe1234-bad2-4fc2-9142-990d3d920fb7".replace("-", "") + "ddbb7698-bad2-4fc2-9142-990d3d920fb7".replace("-", "")[:20] - print "\nBringing clone of myvol6 offline" + print("\nBringing clone of myvol6 offline") (rc, errlog, errmsg) = sshutil.vol_offline(conn, clone_name) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nDeleting clone of myvol6: %s from SR"% clone_name + print("\nDeleting clone of myvol6: %s from SR"% clone_name) (rc, output, errlog, errmsg) = sshutil.vol_delete(conn, clone_name) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) snap_clone= "XenStorage" + "bebe1234-bad2-4fc2-9142-990d3d920fb7".replace("-", "") + "eeff9012-bad2-4fc2-9142-990d3d92cccc".replace("-", "")[:20] - print "\nDeleting snap-clone of myvol6: %s from SR"% snap_clone + print("\nDeleting snap-clone of myvol6: %s from SR"% snap_clone) (rc, output, errlog, errmsg) = sshutil.vol_delete(conn, snap_clone) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nDeleting snapshot of myvol6 from SR" + print("\nDeleting snapshot of myvol6 from SR") (rc, output, errlog, errmsg) = sshutil.snap_delete(conn, "myvol6", snapname) if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "\nBringing myvol6 offline" + print("\nBringing myvol6 offline") (rc, errlog, errmsg) = sshutil.vol_offline(conn, "myvol6") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) - print "\nDeleting myvol6 from SR" + print("\nDeleting myvol6 from SR") (rc, output, errlog, errmsg) = sshutil.vol_delete(conn, "myvol6") if (rc): - print errmsg + print(errmsg) for id in range(len(errlog)): - print errlog[id] + print(errlog[id]) else: - print output + print(output) - print "Total time elapsed: %is"% (time.time() - start_time) + print("Total time elapsed: %is"% (time.time() - start_time)) loop_count = loop_count - 1 diff --git a/test_support/test_flock.py b/test_support/test_flock.py index 8c490b6fd..e52bdf5c7 100755 --- a/test_support/test_flock.py +++ b/test_support/test_flock.py @@ -1,4 +1,5 @@ #!/usr/bin/python +from __future__ import print_function from flock import WriteLock, ReadLock # @@ -68,7 +69,7 @@ def test_interface(): # Attempt to re-lock should throw try: lock.lock() - except AssertionError, e: + except AssertionError as e: if str(e) != WriteLock.ERROR_ISLOCKED: raise else: @@ -89,7 +90,7 @@ def test_interface(): # Attempt to re-unlock should throw. try: lock.unlock() - except AssertionError, e: + except AssertionError as e: if str(e) != WriteLock.ERROR_NOTLOCKED: raise else: @@ -148,8 +149,8 @@ def test_rwlocking(): if __name__ == "__main__": - print >>sys.stderr, "Running basic interface tests..." + print("Running basic interface tests...", file=sys.stderr) test_interface() - print >>sys.stderr, "Running RW-locking stuff not clear from the manpages..." + print("Running RW-locking stuff not clear from the manpages...", file=sys.stderr) test_rwlocking() - print >>sys.stderr, "OK." + print("OK.", file=sys.stderr) diff --git a/test_support/test_lock.py b/test_support/test_lock.py index 89f929f6d..0ffa43ce9 100644 --- a/test_support/test_lock.py +++ b/test_support/test_lock.py @@ -14,6 +14,7 @@ # You should have received a copy of the GNU Lesser General Public License # along 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 from lock import Lock @@ -33,7 +34,7 @@ def test(): # Second lock shall throw in debug mode. try: lock.acquire() - except AssertionError, e: + except AssertionError as e: if str(e) != flock.WriteLock.ERROR_ISLOCKED: raise else: @@ -44,6 +45,6 @@ def test(): Lock.cleanup() if __name__ == '__main__': - print >>sys.stderr, "Running self tests..." + print("Running self tests...", file=sys.stderr) test() - print >>sys.stderr, "OK." + print("OK.", file=sys.stderr) diff --git a/tests/lvmlib.py b/tests/lvmlib.py index 15977852c..46efdb1d4 100644 --- a/tests/lvmlib.py +++ b/tests/lvmlib.py @@ -74,7 +74,7 @@ def fake_lvcreate(self, args, stdin): parser.add_option("-W", dest='wipe_sig') try: options, args = parser.parse_args(args[1:]) - except SystemExit, e: + except SystemExit as e: self.logger("LVCREATE OPTION PARSING FAILED") return (1, '', str(e)) @@ -105,7 +105,7 @@ def fake_lvremove(self, args, stdin): self.logger(args, stdin) try: options, args = parser.parse_args(args[1:]) - except SystemExit, e: + except SystemExit as e: self.logger("LVREMOVE OPTION PARSING FAILED") return (1, '', str(e)) diff --git a/tests/test_LVHDSR.py b/tests/test_LVHDSR.py index 59c2c4589..3ebb402c0 100644 --- a/tests/test_LVHDSR.py +++ b/tests/test_LVHDSR.py @@ -1,3 +1,4 @@ +from __future__ import print_function import unittest import mock import LVHDSR @@ -7,7 +8,7 @@ class SMLog(object): def __call__(self, *args): - print args + print(args) class Stubs(object): diff --git a/tests/test_blktap2.py b/tests/test_blktap2.py index 27bc53d34..1961bcacb 100644 --- a/tests/test_blktap2.py +++ b/tests/test_blktap2.py @@ -1,3 +1,4 @@ +from __future__ import print_function import errno import json from StringIO import StringIO @@ -69,7 +70,7 @@ def setUp(self): self.addCleanup(mock.patch.stopall) def log(self, message): - print message + print(message) def test_list_no_args(self): """ diff --git a/tests/test_mpath_dmp.py b/tests/test_mpath_dmp.py index 51b88686c..6fc6c2a7b 100644 --- a/tests/test_mpath_dmp.py +++ b/tests/test_mpath_dmp.py @@ -1,6 +1,7 @@ """ Unit tests for mpath dmp """ +from __future__ import print_function import errno import os import unittest @@ -419,7 +420,7 @@ def test_refresh_refresh_error( context.setup_error_codes() def exists(path): - print 'Exists %s' % path + print('Exists %s' % path) if path.startswith('/dev/'): return False diff --git a/tests/test_mpathcount.py b/tests/test_mpathcount.py index 164e1ae6c..4082bf223 100644 --- a/tests/test_mpathcount.py +++ b/tests/test_mpathcount.py @@ -1,6 +1,7 @@ """ Unit tests for mpathcount """ +from __future__ import print_function import errno import os import unittest diff --git a/tests/test_on_slave.py b/tests/test_on_slave.py index 54ebcd388..6ad197fde 100644 --- a/tests/test_on_slave.py +++ b/tests/test_on_slave.py @@ -1,3 +1,4 @@ +from __future__ import print_function import errno import unittest import mock @@ -16,7 +17,7 @@ class Test_on_slave_is_open(unittest.TestCase): MOCK_IMPORTS = ['SRCommand', 'SR', 'NFSSR', 'EXTSR', 'LVHDSR', 'blktap2'] def fake_import(self, name, *args): - print 'Asked to import {}'.format(name) + print('Asked to import {}'.format(name)) if name in Test_on_slave_is_open.MOCK_IMPORTS: if name not in self.mocks: self.mocks[name] = mock.MagicMock() diff --git a/tests/test_xs_errors.py b/tests/test_xs_errors.py index 3c2cf045e..86385346c 100644 --- a/tests/test_xs_errors.py +++ b/tests/test_xs_errors.py @@ -11,7 +11,7 @@ def test_without_xml_defs(self, context): raised_exception = None try: xs_errors.XenError('blah') - except Exception, e: + except Exception as e: raised_exception = e self.assertTrue("No XML def file found" in str(e)) @@ -23,7 +23,7 @@ def test_xml_defs(self, context): raised_exception = None try: raise xs_errors.XenError('SRInUse') - except Exception, e: + except Exception as e: raised_exception = e self.assertTrue("The SR device is currently in use" in str(e))