當前位置: 首頁>>代碼示例>>Python>>正文


Python exceptions.NotFound方法代碼示例

本文整理匯總了Python中novaclient.exceptions.NotFound方法的典型用法代碼示例。如果您正苦於以下問題:Python exceptions.NotFound方法的具體用法?Python exceptions.NotFound怎麽用?Python exceptions.NotFound使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在novaclient.exceptions的用法示例。


在下文中一共展示了exceptions.NotFound方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: terminate_instances

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def terminate_instances(context, instance_id):
    instance_ids = set(instance_id)
    instances = ec2utils.get_db_items(context, 'i', instance_ids)

    nova = clients.nova(context)
    state_changes = []
    for instance in instances:
        if instance.get('disable_api_termination'):
            message = _("The instance '%s' may not be terminated. Modify its "
                        "'disableApiTermination' instance attribute and try "
                        "again.") % instance['id']
            raise exception.OperationNotPermitted(message=message)
    for instance in instances:
        try:
            os_instance = nova.servers.get(instance['os_id'])
        except nova_exception.NotFound:
            os_instance = None
        else:
            os_instance.delete()
        state_change = _format_state_change(instance, os_instance)
        state_changes.append(state_change)

    # NOTE(ft): don't delete items from DB until they disappear from OS.
    # They will be auto deleted by a describe operation
    return {'instancesSet': state_changes} 
開發者ID:openstack,項目名稱:ec2-api,代碼行數:27,代碼來源:instance.py

示例2: _format_state_change

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def _format_state_change(instance, os_instance):
    if os_instance:
        prev_state = _cloud_state_description(getattr(os_instance,
                                                      'OS-EXT-STS:vm_state'))
        try:
            os_instance.get()
            curr_state = _cloud_state_description(
                getattr(os_instance, 'OS-EXT-STS:vm_state'))
        except nova_exception.NotFound:
            curr_state = _cloud_state_description(vm_states_WIPED_OUT)
    else:
        prev_state = curr_state = _cloud_state_description(vm_states_WIPED_OUT)
    return {
        'instanceId': instance['id'],
        'previousState': prev_state,
        'currentState': curr_state,
    } 
開發者ID:openstack,項目名稱:ec2-api,代碼行數:19,代碼來源:instance.py

示例3: get_ec2_network_interfaces

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def get_ec2_network_interfaces(self, context, instance_ids=None):
        # NOTE(ft): we would be glad to use filters with this describe
        # operation, but:
        # 1. A selective filter by network interface IDs is improper because
        # it leads to rising NotFound exception if at least one of specified
        # network interfaces is obsolete. This is the legal case of describing
        # an instance after its terminating.
        # 2. A general filter by instance ID is unsupported now.
        # 3. A general filter by network interface IDs leads to additional
        # call of DB here to get corresponding network interfaces, but doesn't
        # lead to decrease DB and OS throughtput in called describe operation.
        enis = network_interface_api.describe_network_interfaces(
            context)['networkInterfaceSet']
        ec2_network_interfaces = collections.defaultdict(list)
        for eni in enis:
            if (eni['status'] == 'in-use' and
                    (not instance_ids or
                     eni['attachment']['instanceId'] in instance_ids)):
                ec2_network_interfaces[
                    eni['attachment']['instanceId']].append(eni)
        return ec2_network_interfaces 
開發者ID:openstack,項目名稱:ec2-api,代碼行數:23,代碼來源:instance.py

示例4: validate_flavor

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def validate_flavor(self, flavor_id):
        """Validates that a flavor exists in nova.

        :param flavor_id: ID of the flavor to lookup in nova.
        :raises: NotFound
        :returns: None
        """
        try:
            self.flavor_manager.get(flavor_id)
        except nova_exceptions.NotFound:
            LOG.info('Flavor %s was not found in nova.', flavor_id)
            raise exceptions.InvalidSubresource(resource='Nova flavor',
                                                id=flavor_id)
        except Exception as e:
            LOG.exception('Nova reports a failure getting flavor details for '
                          'flavor ID %s: %s', flavor_id, e)
            raise 
開發者ID:openstack,項目名稱:octavia,代碼行數:19,代碼來源:nova_driver.py

示例5: validate_availability_zone

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def validate_availability_zone(self, availability_zone):
        """Validates that an availability zone exists in nova.

        :param availability_zone: Name of the availability zone to lookup.
        :raises: NotFound
        :returns: None
        """
        try:
            compute_zones = [
                a.zoneName for a in self.availability_zone_manager.list(
                    detailed=False)]
            if availability_zone not in compute_zones:
                LOG.info('Availability zone %s was not found in nova. %s',
                         availability_zone, compute_zones)
                raise exceptions.InvalidSubresource(
                    resource='Nova availability zone', id=availability_zone)
        except Exception as e:
            LOG.exception('Nova reports a failure getting listing '
                          'availability zones: %s', e)
            raise 
開發者ID:openstack,項目名稱:octavia,代碼行數:22,代碼來源:nova_driver.py

示例6: delete_vminstance

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def delete_vminstance(self, vm_id):
        '''Removes a VM instance from VIM. Returns the old identifier
        '''
        #print "osconnector: Getting VM from VIM"
        try:
            self._reload_connection()
            #delete VM ports attached to this networks before the virtual machine
            ports = self.neutron.list_ports(device_id=vm_id)
            for p in ports['ports']:
                try:
                    self.neutron.delete_port(p["id"])
                except Exception as e:
                    self.logger.error("Error deleting port: " + type(e).__name__ + ": "+  str(e))
            self.nova.servers.delete(vm_id)
            return vm_id
        except (nvExceptions.NotFound, ksExceptions.ClientException, nvExceptions.ClientException) as e:
            self._format_exception(e)
        #TODO insert exception vimconn.HTTP_Unauthorized
        #if reaching here is because an exception 
開發者ID:nfvlabs,項目名稱:openmano,代碼行數:21,代碼來源:vimconn_openstack.py

示例7: delete_user

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def delete_user(self, user_id):
        '''Delete a user from openstack VIM'''
        '''Returns the user identifier'''
        if self.debug:
            print "osconnector: Deleting  a  user from VIM"
        try:
            self._reload_connection()
            self.keystone.users.delete(user_id)
            return 1, user_id
        except ksExceptions.ConnectionError as e:
            error_value=-vimconn.HTTP_Bad_Request
            error_text= type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0]))
        except ksExceptions.NotFound as e:
            error_value=-vimconn.HTTP_Not_Found
            error_text= type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0]))
        except ksExceptions.ClientException as e: #TODO remove
            error_value=-vimconn.HTTP_Bad_Request
            error_text= type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0]))
        #TODO insert exception vimconn.HTTP_Unauthorized
        #if reaching here is because an exception
        if self.debug:
            print "delete_tenant " + error_text
        return error_value, error_text 
開發者ID:nfvlabs,項目名稱:openmano,代碼行數:25,代碼來源:vimconn_openstack.py

示例8: get_hosts_info

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def get_hosts_info(self):
        '''Get the information of deployed hosts
        Returns the hosts content'''
        if self.debug:
            print "osconnector: Getting Host info from VIM"
        try:
            h_list=[]
            self._reload_connection()
            hypervisors = self.nova.hypervisors.list()
            for hype in hypervisors:
                h_list.append( hype.to_dict() )
            return 1, {"hosts":h_list}
        except nvExceptions.NotFound as e:
            error_value=-vimconn.HTTP_Not_Found
            error_text= (str(e) if len(e.args)==0 else str(e.args[0]))
        except (ksExceptions.ClientException, nvExceptions.ClientException) as e:
            error_value=-vimconn.HTTP_Bad_Request
            error_text= type(e).__name__ + ": "+  (str(e) if len(e.args)==0 else str(e.args[0]))
        #TODO insert exception vimconn.HTTP_Unauthorized
        #if reaching here is because an exception
        if self.debug:
            print "get_hosts_info " + error_text
        return error_value, error_text 
開發者ID:nfvlabs,項目名稱:openmano,代碼行數:25,代碼來源:vimconn_openstack.py

示例9: get

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def get(self, instance_id):
        """
        Returns an instance given its id.
        """
        try:
            os_instance = self.provider.nova.servers.get(instance_id)
        except NovaNotFound:
            log.debug("Instance %s was not found.", instance_id)
            return None
        if (getattr(os_instance,
                    'OS-EXT-AZ:availability_zone', "")
                != self.provider.service_zone_name(self)):
            log.debug("Instance %s was found in availability zone '%s' while "
                      "the OpenStack provider is in zone '%s'",
                      instance_id,
                      getattr(os_instance, 'OS-EXT-AZ:availability_zone', ""),
                      self.provider.service_zone_name(self))
            return None
        return OpenStackInstance(self.provider, os_instance) 
開發者ID:CloudVE,項目名稱:cloudbridge,代碼行數:21,代碼來源:services.py

示例10: get_template

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def get_template(self, name=None, id=None):
        """
        Get a template by name OR id
        """
        if name:
            matches = self.find_templates(name)
            if not matches:
                raise ImageNotFoundError(name)
            elif len(matches) > 1:
                raise MultipleImagesError(name)
            result = matches[0]
        elif id:
            try:
                raw_image = self.api.images.get(id)
            except os_exceptions.NotFound:
                raise ImageNotFoundError(id)
            result = OpenstackImage(system=self, uuid=raw_image.id, raw=raw_image)
        else:
            raise AttributeError("Must specify either 'name' or 'id' with get_template")
        return result 
開發者ID:RedHatQE,項目名稱:wrapanapi,代碼行數:22,代碼來源:openstack.py

示例11: create_flavor

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def create_flavor(conn: OSConnection, name: str, ram_size: int, hdd_size: int, cpu_count: int) -> None:
    """create flavor, if doesn't exisis yet

    parameters:
        nova: nova connection
        name: str - flavor name
        ram_size: int - ram size (UNIT?)
        hdd_size: int - root hdd size (UNIT?)
        cpu_count: int - cpu cores

    returns: None
    """
    try:
        conn.nova.flavors.find(name)
        return
    except NotFound:
        pass

    conn.nova.flavors.create(name, cpu_count, ram_size, hdd_size) 
開發者ID:Mirantis,項目名稱:disk_perf_test_tool,代碼行數:21,代碼來源:openstack_api.py

示例12: _get_validated_flavor

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def _get_validated_flavor(self, config, clients, param_name):

        from novaclient import exceptions as nova_exc

        flavor_value = config.get("args", {}).get(param_name)
        if not flavor_value:
            self.fail("Parameter %s is not specified." % param_name)
        try:
            flavor_processor = openstack_types.Flavor(
                context={"admin": {"credential": clients.credential}})
            flavor_id = flavor_processor.pre_process(flavor_value, config={})
            flavor = clients.nova().flavors.get(flavor=flavor_id)
            return flavor
        except (nova_exc.NotFound, exceptions.InvalidScenarioArgument):
            try:
                return self._get_flavor_from_context(config, flavor_value)
            except validation.ValidationError:
                pass
            self.fail("Flavor '%s' not found" % flavor_value) 
開發者ID:openstack,項目名稱:rally-openstack,代碼行數:21,代碼來源:validators.py

示例13: test__get_validated_flavor_not_found

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def test__get_validated_flavor_not_found(self, mock_flavor):
        mock_flavor.return_value.pre_process.return_value = "flavor_id"

        clients = mock.MagicMock()
        clients.nova().flavors.get.side_effect = nova_exc.NotFound("")

        e = self.assertRaises(
            validators.validation.ValidationError,
            self.validator._get_validated_flavor,
            self.config, clients, "flavor")
        self.assertEqual("Flavor '%s' not found" %
                         self.config["args"]["flavor"],
                         e.message)
        mock_flavor_obj = mock_flavor.return_value
        mock_flavor_obj.pre_process.assert_called_once_with(
            self.config["args"]["flavor"], config={}) 
開發者ID:openstack,項目名稱:rally-openstack,代碼行數:18,代碼來源:test_validators.py

示例14: translate_server_exception

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def translate_server_exception(method):
    """Transforms the exception for the instance.

    Note: keeps its traceback intact.
    """

    @six.wraps(method)
    def wrapper(self, ctx, instance_id, *args, **kwargs):
        try:
            res = method(self, ctx, instance_id, *args, **kwargs)
            return res
        except nova_exception.ClientException as e:
            if isinstance(e, nova_exception.NotFound):
                raise exception.InstanceNotFound(instance_id=instance_id)
            elif isinstance(e, nova_exception.BadRequest):
                raise exception.InvalidInput(reason=six.text_type(e))
            else:
                raise exception.ManilaException(e)

    return wrapper 
開發者ID:openstack,項目名稱:manila,代碼行數:22,代碼來源:nova.py

示例15: delete_key_pair

# 需要導入模塊: from novaclient import exceptions [as 別名]
# 或者: from novaclient.exceptions import NotFound [as 別名]
def delete_key_pair(context, key_name):
    nova = clients.nova(context)
    try:
        nova.keypairs.delete(key_name)
    except nova_exception.NotFound:
        # aws returns true even if the key doesn't exist
        pass
    return True 
開發者ID:openstack,項目名稱:ec2-api,代碼行數:10,代碼來源:key_pair.py


注:本文中的novaclient.exceptions.NotFound方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。