def test_safe_exception_translated(self, mock_languages, mock_translate): def fake_translate(value, locale): return "I've been translated!" mock_translate.side_effect = fake_translate # Create an exception, passing a translatable message with a # known value we can test for later. safe_exception = exception.NotFound('Should be translated.') safe_exception.safe = True safe_exception.code = 404 req = webob.Request.blank('/') def raiser(*args, **kwargs): raise safe_exception wrapper = patron.api.openstack.FaultWrapper(raiser) response = req.get_response(wrapper) # The text of the exception's message attribute (replaced # above with a non-default value) should be passed to # translate(). mock_translate.assert_any_call(u'Should be translated.', None) # The return value from translate() should appear in the response. self.assertIn("I've been translated!", unicode(response.body))
def _get_resource_for_node(self, nodename): """Gets the resource information for the specific node.""" resource = self._resources.get(nodename) if not resource: msg = _("The resource %s does not exist") % nodename raise exception.NotFound(msg) return resource
def __init__(self, ldap_object, domain): super(DomainEntry, self).__init__(ldap_object) entry = self._get_tuple_for_domain(self.lobj, domain) if not entry: raise exception.NotFound() self._set_tuple(entry) assert(entry[1]['associatedDomain'][0] == domain) self.qualified_domain = domain
def _get_vm(self, conn_v2, vm_name): vms = conn_v2.Msvm_ComputerSystem(ElementName=vm_name) n = len(vms) if not n: raise exception.NotFound(_('VM not found: %s') % vm_name) elif n > 1: raise vmutils.HyperVException(_('Duplicate VM name found: %s') % vm_name) return vms[0]
def _translate_plain_exception(exc_value): if isinstance(exc_value, (glanceclient.exc.Forbidden, glanceclient.exc.Unauthorized)): return exception.Forbidden(six.text_type(exc_value)) if isinstance(exc_value, glanceclient.exc.NotFound): return exception.NotFound(six.text_type(exc_value)) if isinstance(exc_value, glanceclient.exc.BadRequest): return exception.Invalid(six.text_type(exc_value)) return exc_value
def modify_address(self, name, address): names = self.ldap_tuple[1]['associatedDomain'] if not names: raise exception.NotFound() if len(names) == 1: self.lobj.modify_s(self.dn, [(ldap.MOD_REPLACE, 'aRecord', [utils.utf8(address)])]) else: self.remove_name(name) self.parent.add_entry(name, address)
def remove_name(self, name): names = self.ldap_tuple[1]['associatedDomain'] if not names: raise exception.NotFound() if len(names) > 1: # We just have to remove the requested domain. self.lobj.modify_s(self.dn, [(ldap.MOD_DELETE, 'associatedDomain', self._qualify(utils.utf8(name)))]) if (self.rdn[1] == name): # We just removed the rdn, so we need to move this entry. names.remove(self._qualify(name)) newrdn = 'dc=%s' % self._dequalify(names[0]) self.lobj.modrdn_s(self.dn, [newrdn]) else: # We should delete the entire record. self.lobj.delete_s(self.dn)
def _service_start_mocks(self): service_create = { 'host': self.host, 'binary': self.binary, 'topic': self.topic, 'report_count': 0 } service_ref = { 'host': self.host, 'binary': self.binary, 'topic': self.topic, 'report_count': 0, 'id': 1 } db.service_get_by_host_and_binary(mox.IgnoreArg(), self.host, self.binary).AndRaise( exception.NotFound()) db.service_create(mox.IgnoreArg(), service_create).AndReturn(service_ref) return service_ref
def _lookup_vm_check(self, vm_name): vm = self._lookup_vm(vm_name) if not vm: raise exception.NotFound(_('VM not found: %s') % vm_name) return vm
def host_maintenance_mode(self, host, mode): """Start/Stop host maintenance window. On start, it triggers guest VMs evacuation. """ if not mode: return 'off_maintenance' host_list = [ host_ref for host_ref in self._session.host.get_all() if host_ref != self._session.host_ref ] migrations_counter = vm_counter = 0 ctxt = context.get_admin_context() for vm_ref, vm_rec in vm_utils.list_vms(self._session): for host_ref in host_list: try: # Ensure only guest instances are migrated uuid = vm_rec['other_config'].get('patron_uuid') if not uuid: name = vm_rec['name_label'] uuid = _uuid_find(ctxt, host, name) if not uuid: LOG.info( _LI('Instance %(name)s running on ' '%(host)s could not be found in ' 'the database: assuming it is a ' 'worker VM and skip ping migration ' 'to a new host'), { 'name': name, 'host': host }) continue instance = objects.Instance.get_by_uuid(ctxt, uuid) vm_counter = vm_counter + 1 aggregate = objects.AggregateList.get_by_host( ctxt, host, key=pool_states.POOL_FLAG) if not aggregate: msg = _('Aggregate for host %(host)s count not be' ' found.') % dict(host=host) raise exception.NotFound(msg) dest = _host_find(ctxt, self._session, aggregate[0], host_ref) instance.host = dest instance.task_state = task_states.MIGRATING instance.save() self._session.VM.pool_migrate(vm_ref, host_ref, {"live": "true"}) migrations_counter = migrations_counter + 1 instance.vm_state = vm_states.ACTIVE instance.save() break except self._session.XenAPI.Failure: LOG.exception( _LE('Unable to migrate VM %(vm_ref)s ' 'from %(host)s'), { 'vm_ref': vm_ref, 'host': host }) instance.host = host instance.vm_state = vm_states.ACTIVE instance.save() if vm_counter == migrations_counter: return 'on_maintenance' else: raise exception.NoValidHost(reason='Unable to find suitable ' 'host for VMs evacuation')
def return_non_existing_address(*args, **kwarg): raise exception.NotFound()
class SimpleTenantUsageControllerTestV21(test.TestCase): controller = simple_tenant_usage_v21.SimpleTenantUsageController() def setUp(self): super(SimpleTenantUsageControllerTestV21, self).setUp() self.context = context.RequestContext('fakeuser', 'fake-project') self.baseinst = get_fake_db_instance(START, STOP, instance_id=1, tenant_id=self.context.project_id, vm_state=vm_states.DELETED) # convert the fake instance dict to an object self.inst_obj = objects.Instance._from_db_object( self.context, objects.Instance(), self.baseinst) def test_get_flavor_from_sys_meta(self): # Non-deleted instances get their type information from their # system_metadata with mock.patch.object(db, 'instance_get_by_uuid', return_value=self.baseinst): flavor = self.controller._get_flavor(self.context, self.inst_obj, {}) self.assertEqual(objects.Flavor, type(flavor)) self.assertEqual(FAKE_INST_TYPE['id'], flavor.id) def test_get_flavor_from_non_deleted_with_id_fails(self): # If an instance is not deleted and missing type information from # system_metadata, then that's a bug self.inst_obj.system_metadata = {} self.assertRaises(exception.NotFound, self.controller._get_flavor, self.context, self.inst_obj, {}) @mock.patch('patron.objects.Instance.get_flavor', side_effect=exception.NotFound()) def test_get_flavor_from_deleted_with_notfound(self, fake_get_flavor): self.inst_obj.deleted = 1 flavor = self.controller._get_flavor(self.context, self.inst_obj, {}) self.assertEqual(objects.Flavor, type(flavor)) self.assertEqual(FAKE_INST_TYPE['id'], flavor.id) def test_get_flavor_from_deleted_with_id(self): # Deleted instances may not have type info in system_metadata, # so verify that they get their type from a lookup of their # instance_type_id self.inst_obj.system_metadata = {} self.inst_obj.deleted = 1 flavor = self.controller._get_flavor(self.context, self.inst_obj, {}) self.assertEqual(objects.Flavor, type(flavor)) self.assertEqual(FAKE_INST_TYPE['id'], flavor.id) def test_get_flavor_from_deleted_with_id_of_deleted(self): # Verify the legacy behavior of instance_type_id pointing to a # missing type being non-fatal self.inst_obj.system_metadata = {} self.inst_obj.deleted = 1 self.inst_obj.instance_type_id = 99 flavor = self.controller._get_flavor(self.context, self.inst_obj, {}) self.assertIsNone(flavor)
def __init__(self, virtapi, scheme="https"): super(VMwareVCDriver, self).__init__(virtapi) if (CONF.vmware.host_ip is None or CONF.vmware.host_username is None or CONF.vmware.host_password is None): raise Exception( _("Must specify host_ip, host_username and " "host_password to use vmwareapi.VMwareVCDriver")) self._datastore_regex = None if CONF.vmware.datastore_regex: try: self._datastore_regex = re.compile(CONF.vmware.datastore_regex) except re.error: raise exception.InvalidInput( reason=_("Invalid Regular Expression %s") % CONF.vmware.datastore_regex) self._session = VMwareAPISession(scheme=scheme) # Update the PBM location if necessary if CONF.vmware.pbm_enabled: self._update_pbm_location() self._validate_configuration() # Get the list of clusters to be used self._cluster_names = CONF.vmware.cluster_name if len(self._cluster_names) > 1: versionutils.report_deprecated_feature( LOG, _LW('The "cluster_name" setting should have only one ' 'cluster name. The capability of allowing ' 'multiple clusters may be dropped in the ' 'Liberty release.')) self.dict_mors = vm_util.get_all_cluster_refs_by_name( self._session, self._cluster_names) if not self.dict_mors: raise exception.NotFound( _("All clusters specified %s were not" " found in the vCenter") % self._cluster_names) # Check if there are any clusters that were specified in the patron.conf # but are not in the vCenter, for missing clusters log a warning. clusters_found = [v.get('name') for k, v in self.dict_mors.iteritems()] missing_clusters = set(self._cluster_names) - set(clusters_found) if missing_clusters: LOG.warning( _LW("The following clusters could not be found in the " "vCenter %s"), list(missing_clusters)) # The _resources is used to maintain the vmops, volumeops and vcstate # objects per cluster self._resources = {} self._resource_keys = set() self._virtapi = virtapi self._update_resources() # The following initialization is necessary since the base class does # not use VC state. first_cluster = self._resources.keys()[0] self._vmops = self._resources.get(first_cluster).get('vmops') self._volumeops = self._resources.get(first_cluster).get('volumeops') self._vc_state = self._resources.get(first_cluster).get('vcstate') # Register the OpenStack extension self._register_openstack_extension()
def remove_entry(self, name): entry = self.subentry_with_name(name) if not entry: raise exception.NotFound() entry.remove_name(name) self.update_soa()