def test_deactivate_noref_withbugcleanup_retry(self, lvsystem, mock_pread): # Arrange self.__create_test_volume(lvsystem) self.mock_exists.return_value = True self.mock_lexists.return_value = True mock_pread.side_effect = [ 0, util.CommandException(0), util.CommandException(1), 0 ] # Act lvutil.deactivateNoRefcount( 'VG_XenStorage-b3b18d06-b2ba-5b67-f098-3cdd5087a2a7/volume')
def test_attach_smb_version_fallback_error(self, context, _checkmount, pread, _checkTargetStr, makedirs): """ Fall back scenario negative case from xe-sr-mount with smb3 diabled and smb1 disabled. """ context.setup_error_codes() smbsr = self.create_smbisosr(atype='cifs') pread.side_effect = [util.CommandException(errno.EHOSTDOWN), \ util.CommandException(errno.EHOSTDOWN)] _checkmount.side_effect = [False, True] with self.assertRaises(util.CommandException): smbsr.attach(None)
def test_multi_refresh_on_slaves_deactivate_error(self): vgName = "test_vg" sr_uuid = str(uuid.uuid4()) vdi_uuid = str(uuid.uuid4()) lv_name = 'test_lv' lock_ref = lvhdutil.NS_PREFIX_LVM + sr_uuid self.mock_lvmcache.deactivate.side_effect = util.CommandException( errno.EIO, 'activate') args = { "vgName": vgName, "action1": "activate", "uuid1": vdi_uuid, "ns1": lock_ref, "lvName1": lv_name, "action2": "refresh", "lvName2": lv_name, "action3": "deactivate", "uuid3": vdi_uuid, "ns3": lock_ref, "lvName3": lv_name } with self.assertRaises(util.CommandException): on_slave.multi(self.session, args) self.mock_lvmcache.activate.assert_called_once_with( lock_ref, vdi_uuid, lv_name, False) self.mock_lvmcache.activateNoRefcount.assert_called_once_with( lv_name, True) self.mock_lvmcache.deactivate.assert_called_once_with( lock_ref, vdi_uuid, lv_name, False)
def test_multi_rename_refresh_error(self, mock_refcount): vgName = "test_vg" old_name_lv = "old-lv-name" vdi_fileName = "test-vdi.vhd" origParentUuid = str(uuid.uuid4()) vdi_uuid = str(uuid.uuid4()) lock_ref = lvhdutil.NS_PREFIX_LVM + vdi_uuid self.mock_lvmcache.activateNoRefcount.side_effect = util.CommandException( errno.EIO, 'activate') args = { "vgName": vgName, "action1": "deactivateNoRefcount", "lvName1": old_name_lv, "action2": "refresh", "lvName2": vdi_fileName, "action3": "cleanupLockAndRefcount", "uuid3": origParentUuid, "ns3": lock_ref } with self.assertRaises(util.CommandException): on_slave.multi(self.session, args) self.mock_lvmcache.deactivateNoRefcount.assert_called_once_with( old_name_lv) self.assertEqual(0, mock_refcount.reset.call_count)
def gen_uuid_from_serial(iqn, serial): if len(serial) < SUFFIX_LEN: raise util.CommandException(1) prefix = gen_hash(iqn, PREFIX_LEN) suffix = gen_hash(serial, SUFFIX_LEN) str = prefix.encode("hex") + suffix.encode("hex") return str[0:8]+'-'+str[8:12]+'-'+str[12:16]+'-'+str[16:20]+'-'+str[20:32]
def test_mount_mountpoint_isdir(self, mock_time, mock_lock, mock_isdir): # Not sure that the code rerying in an ioretry loop in the case of a # missing dir is correct? mock_isdir.side_effect = util.CommandException(errno.EIO, "Not a directory") smbsr = self.create_smbsr() with self.assertRaises(SMBSR.SMBException) as cm: smbsr.mount()
def test_mount_mountpoint_isdir(self, mock_isdir): mock_isdir = mock.Mock( side_effect=util.CommandException(errno.EIO, "Not a directory")) smbsr = self.create_smbsr() try: smbsr.mount() except Exception, exc: self.assertTrue(isinstance(exc, SMBSR.SMBException))
def test_check_server_service_first_call_exception(self, pread, sleep): pread.side_effect = [ util.CommandException(errno.EPIPE), " 100003 4,3,2 udp6,tcp6,udp,tcp nfs superuser" ] service_found = nfs.check_server_service('aServer') self.assertTrue(service_found) self.assertEqual(len(pread.mock_calls), 2)
def test_attach_smb_version_fallback_with_smb_1_3_disabled( self, context, _checkmount, pread, _checkTargetStr, makedirs, gen_uuid): """ Fall back scenario from XC/XE CLI with smb3 diabled and smb1 disabled. """ context.setup_error_codes() smbsr = self.create_smbisosr(atype='cifs') pread.side_effect = [util.CommandException(errno.EHOSTDOWN), \ util.CommandException(errno.EHOSTDOWN), util.CommandException(errno.EHOSTDOWN)] _checkmount.side_effect = [False, True] with self.assertRaises(SR.SROSError) as context: smbsr.attach(None) self.assertEqual(context.exception.errno, 222) self.assertEqual( str(context.exception), 'Could not mount the directory specified in Device Configuration [opterr=exec failed]' )
def test_attach_smb_via_xemount_no_version_fallback( self, context, _checkmount, pread, _checkTargetStr, makedirs, gen_uuid): """ Fall back scenario from xe-sr-mount with smb3 diabled and smb1 enabled. """ context.setup_error_codes() smbsr = self.create_smbisosr( options='-o username=administrator,password=password') pread.side_effect = iter([util.CommandException(errno.EHOSTDOWN), " "])
def test_resize_exception(self, context, mock_cbt): # Create the test object self.vdi = TestVDI(self.sr, self.vdi_uuid) # Set initial state self._set_initial_state(self.vdi, True) size = 2093050 mock_cbt.side_effect = util.CommandException(errno.EINVAL) self.vdi.resize_cbt(self.sr_uuid, self.vdi_uuid, size) self._check_setting_state(self.vdi, False) self.xenapi.message.create.assert_called_once()
def test_attach_smb_version_fallback_with_smb_3_disabled( self, context, updateSMBVersInPBDConfig, _checkmount, pread, _checkTargetStr, makedirs, gen_uuid): """ Fall back scenario from XC/XE CLI with smb3 diabled and smb1 enabled. """ context.setup_error_codes() smbsr = self.create_smbisosr(atype='cifs') pread.side_effect = [util.CommandException(errno.EHOSTDOWN), " "] _checkmount.side_effect = [False, True] smbsr.attach(None)
def activateNoRefcount(path, refresh): cmd = [CMD_LVCHANGE, "-ay", path] if refresh: cmd.append("--refresh") text = util.pread2(cmd) if not _checkActive(path): raise util.CommandException(-1, str(cmd), "LV not activated") if refresh: mapperDevice = path[5:].replace("-", "--").replace("/", "-") cmd = [CMD_DMSETUP, "table", mapperDevice] ret = util.pread(cmd) util.SMlog("DM table for %s: %s" % (path, ret.strip()))
def soft_mount(mountpoint, remoteserver, remotepath, transport, useroptions='', timeout=None, nfsversion=DEFAULT_NFSVERSION, retrans=None): """Mount the remote NFS export at 'mountpoint'. The 'timeout' param here is in deciseconds (tenths of a second). See nfs(5) for details. """ try: if not util.ioretry(lambda: util.isdir(mountpoint)): util.ioretry(lambda: util.makedirs(mountpoint)) except util.CommandException as inst: raise NfsException("Failed to make directory: code is %d" % inst.code) # Wait for NFS service to be available try: if not check_server_service(remoteserver): raise util.CommandException(code=errno.EOPNOTSUPP, reason="No NFS service on host") except util.CommandException as inst: raise NfsException("Failed to detect NFS service on server %s" % remoteserver) mountcommand = 'mount.nfs' if nfsversion == '4': mountcommand = 'mount.nfs4' if nfsversion == '4.1': mountcommand = 'mount.nfs4' options = "soft,proto=%s,vers=%s" % ( transport, nfsversion) options += ',acdirmin=0,acdirmax=0' if timeout != None: options += ",timeo=%s" % timeout if retrans != None: options += ",retrans=%s" % retrans if useroptions != '': options += ",%s" % useroptions try: util.ioretry(lambda: util.pread([mountcommand, "%s:%s" % (remoteserver, remotepath), mountpoint, "-o", options]), errlist=[errno.EPIPE, errno.EIO], maxretry=2, nofail=True) except util.CommandException as inst: raise NfsException("mount failed with return code %d" % inst.code)
def test_deactivate_noref_withbugcleanup_retry_fail( self, lvsystem, mock_pread, mock_sleep, mock_symlink): # Arrange self.__create_test_volume(lvsystem) self.mock_exists.return_value = True self.mock_lexists.return_value = False side_effect = [0, util.CommandException(0)] side_effect += 11 * [ util.CommandException(1), util.CommandException(0) ] mock_pread.side_effect = side_effect # Act with self.assertRaises(util.CommandException): lvutil.deactivateNoRefcount( 'VG_XenStorage-b3b18d06-b2ba-5b67-f098-3cdd5087a2a7/volume') # Assert mock_symlink.assert_called_once_with( mock.ANY, 'VG_XenStorage-b3b18d06-b2ba-5b67-f098-3cdd5087a2a7/volume')
def test_activate_noref_IO_error_reported(self, lvsystem, mock_cmd_lvm): # Arrange self.__create_test_volume(lvsystem) self.mock_exists.return_value = True mock_cmd_lvm.side_effect = [ util.CommandException(5, 'lvchange', "Device not found") ] # Act with self.assertRaises(util.CommandException) as ce: lvutil.activateNoRefcount(TEST_VOL, False) self.assertEqual(5, ce.exception.code)
def activateNoRefcount(path, refresh): cmd = [CMD_LVCHANGE, "-ay", path] text = cmd_lvm(cmd) if not _checkActive(path): raise util.CommandException(-1, str(cmd), "LV not activated") if refresh: # Override slave mode lvm.conf for this command os.environ['LVM_SYSTEM_DIR'] = MASTER_LVM_CONF text = cmd_lvm([CMD_LVCHANGE, "--refresh", path]) mapperDevice = path[5:].replace("-", "--").replace("/", "-") cmd = [CMD_DMSETUP, "table", mapperDevice] ret = util.pread(cmd) util.SMlog("DM table for %s: %s" % (path, ret.strip())) # Restore slave mode lvm.conf os.environ['LVM_SYSTEM_DIR'] = DEF_LVM_CONF
def test_attach_smb_version_fallback_with_smb_3_disabled( self, context, updateSMBVersInPBDConfig, _checkmount, pread, _checkTargetStr, makedirs, gen_uuid): """ Fall back scenario from XC/XE CLI with smb3 diabled and smb1 enabled. """ context.setup_error_codes() smbsr = self.create_smbisosr(atype='cifs') pread.side_effect = iter([util.CommandException(errno.EHOSTDOWN), " "]) _checkmount.side_effect = [False, True] smbsr.attach(None) pread.assert_called_with([ 'mount.cifs', '\\aServer\x07Location', '/var/run/sr-mount/asr_uuid', '-o', 'cache=none,guest,vers=1.0' ], True, new_env=None)
def test_clone_nospace_snap_2(self, mock_blktap, mock_getDepth, mock_pathexists, mock_query_p_uuid, mock_uuid, mock_snap): # Arrange sr_uuid = str(uuid.uuid4()) vdi_uuid = str(uuid.uuid4()) sr = mock.MagicMock() sr.path = "sr_path" vdi = FakeFileVDI(sr, vdi_uuid) vdi.sr = sr mock_getDepth.return_value = 1 mock_pathexists.return_value = True new_vdi_uuid = str(uuid.uuid4()) clone_vdi_uuid = str(uuid.uuid4()) mock_uuid.side_effect = [clone_vdi_uuid, new_vdi_uuid] grandp_uuid = str(uuid.uuid4()) mock_snap.side_effect = [None, util.CommandException(errno.ENOSPC)] self.mock_gethidden.return_value = False real_stat = os.stat def my_stat(tgt): if tgt.endswith('.vhd'): return os.stat_result( (stat.S_IFREG, 0, 0, 1, 0, 0, 1024, 0, 0, 0)) return real_stat(tgt) # Act with self.assertRaises(SR.SROSError) as srose, mock.patch( 'FileSR.os.stat') as mock_stat: mock_stat.side_effect = my_stat clone_xml = vdi.clone(sr_uuid, vdi_uuid) # Assert self.mock_os_link.assert_called_with('sr_path/%s.vhd' % vdi_uuid, 'sr_path/%s.vhd' % new_vdi_uuid) self.assertEqual(1, self.mock_os_unlink.call_count) self.assertEqual(2, mock_snap.call_count) self.mock_os_rename.assert_has_calls([ mock.call('sr_path/%s.vhd.new' % vdi_uuid, 'sr_path/%s.vhd' % vdi_uuid), mock.call('sr_path/%s.vhd' % new_vdi_uuid, 'sr_path/%s.vhd' % vdi_uuid) ])
def extend(ssize, path): if not _checkActive(path): raise util.CommandException(-1, "extend", "LV not activated") try: # Override slave mode lvm.conf for this command os.environ['LVM_SYSTEM_DIR'] = MASTER_LVM_CONF #cmd = cmd_lvm([CMD_LVEXTEND, ssize, path]) try: #util.pread(cmd) cmd_lvm([CMD_LVEXTEND, ssize, path], pread_func=util.pread) return True except Exception, e: util.SMlog("lvextend failed for %s with error %s." % (path, str(e))) return False finally: # Restore slave mode lvm.conf os.environ['LVM_SYSTEM_DIR'] = DEF_LVM_CONF
def test_activate_noref_metadata_error_retry(self, lvsystem, mock_cmd_lvm, mock_sleep): # Arrange self.__create_test_volume(lvsystem) self.mock_exists.return_value = True metadata_error = """ Incorrect checksum in metadata area header on /dev/sdb at 4096 Failed to read mda header from /dev/sdb Failed to scan VG from /dev/sdb Volume group "VG_XenStorage-94d5c7de-3bee-e7c2-8aeb-d609e7dcd358" not found Cannot process volume group VG_XenStorage-94d5c7de-3bee-e7c2-8aeb-d609e7dcd358""" mock_cmd_lvm.side_effect = [ util.CommandException(5, 'lvchange', metadata_error), '' ] # Act lvutil.activateNoRefcount(TEST_VOL, False)
def test_vdi_delete_bitmap_coalesce_exc(self, context, mock_lock, mock_logcheck, mock_cbt): # Create the test object and initialise self.vdi = TestVDI(self.sr, self.vdi_uuid) self._set_initial_state(self.vdi, True) parent_uuid = "parentUUID" child_uuid = "childUUID" mock_cbt.get_cbt_parent.return_value = parent_uuid mock_cbt.get_cbt_child.return_value = child_uuid parent_log = self.vdi._get_cbt_logpath(parent_uuid) child_log = self.vdi._get_cbt_logpath(child_uuid) mock_logcheck.side_effect = [True, True, True, True] mock_cbt.coalesce_bitmap.side_effect = util.CommandException(errno.EIO) self.vdi.delete(self.sr_uuid, self.vdi_uuid, data_only=False) mock_cbt.set_cbt_child.assert_called_with(parent_log, self.vdi_uuid) mock_cbt.set_cbt_parent.assert_called_with(child_log, self.vdi_uuid) self.assertEqual(0, self.vdi.state_mock._delete_cbt_log.call_count)
def activateNoRefcount(path, refresh): #cmd = cmd_lvm([CMD_LVCHANGE, "-ay", path]) #text = util.pread2(cmd) cmd = [CMD_LVCHANGE, "-ay", path] stateFileAttach = os.getenv('THIN_STATE_FILE_ATTACH', None) if stateFileAttach == "true": cmd.append("--offline") text = cmd_lvm(cmd) if not _checkActive(path): raise util.CommandException(-1, str(cmd), "LV not activated") if refresh: # Override slave mode lvm.conf for this command os.environ['LVM_SYSTEM_DIR'] = MASTER_LVM_CONF #cmd = cmd_lvm([CMD_LVCHANGE, "--refresh", path]) #text = util.pread2(cmd) text = cmd_lvm([CMD_LVCHANGE, "--refresh", path]) mapperDevice = path[5:].replace("-", "--").replace("/", "-") cmd = [CMD_DMSETUP, "table", mapperDevice] ret = util.pread(cmd) util.SMlog("DM table for %s: %s" % (path, ret.strip())) # Restore slave mode lvm.conf os.environ['LVM_SYSTEM_DIR'] = DEF_LVM_CONF
def test_cgclassify_exception_swallow(self, mock_log, mock_pread2): mock_pread2.side_effect = util.CommandException(999) blktap2.Tapdisk.cgclassify(123) mock_pread2.assert_called_with(['cgclassify', '123']) self.assertEquals(mock_log.call_count, 1)
def test_check_server_service_exception(self, pread, sleep): pread.side_effect = [util.CommandException(errno.ENOMEM)] with self.assertRaises(util.CommandException): nfs.check_server_service('aServer')
def _activate(path): cmd = [CMD_LVCHANGE, "-ay", path] cmd_lvm(cmd) if not _checkActive(path): raise util.CommandException(-1, str(cmd), "LV not activated")
def _validate_args(cmd, args, min_args): if len(args) < min_args: raise util.CommandException("Command '%s' requires at least %d arguments, only %d were passed (%d)" % (cmd, min_args, len(args), args))
def gen_uuid_from_string(str): if len(str) < (PREFIX_LEN + SUFFIX_LEN): raise util.CommandException(1) return str[0:8] + '-' + str[8:12] + '-' + str[12:16] + '-' + str[ 16:20] + '-' + str[20:32]
def gen_serial_from_uuid(iqn, uuid): str = uuid.replace('-', '') prefix = gen_hash(iqn, PREFIX_LEN) if str[0:(PREFIX_LEN * 2)].decode("hex") != prefix: raise util.CommandException(1) return str[(PREFIX_LEN * 2):].decode("hex")
def __fist_enospace(self): raise util.CommandException(28, "vhd-util snapshot", reason="No space")