How to use the nova.context function in nova

To help you get started, we’ve selected a few nova examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github openstack / ceilometer / nova_tests / test_notifier.py View on Github external
def test_instance_flavor(self):
        inst = nova_notifier.Instance(context, self.instance)
        self.assertEqual(inst.flavor['name'], 'm1.tiny')
        self.assertEqual(inst.flavor['flavor_id'], '1')
github openstack / nova / nova / api / openstack / compute / legacy_v2 / contrib / os_tenant_networks.py View on Github external
def _get_default_networks(self):
        project_id = CONF.neutron_default_tenant_id
        ctx = nova_context.RequestContext(user_id=None,
                                          project_id=project_id)
        networks = {}
        for n in self.network_api.get_all(ctx):
            networks[n['id']] = n['label']
        return [{'id': k, 'label': v} for k, v in six.iteritems(networks)]
github openstack / nova / nova / api / openstack / compute / legacy_v2 / contrib / availability_zone.py View on Github external
def detail(self, req):
        """Returns a detailed list of availability zone."""
        context = req.environ['nova.context']
        authorize_detail(context)
        # NOTE(alex_xu): back-compatible with db layer hard-code admin
        # permission checks.
        nova_context.require_admin_context(context)
        return self._describe_availability_zones_verbose(context)
github openstack / hacking / xenserver / vm_vdi_cleaner.py View on Github external
def find_orphaned_instances(xenapi):
    """Find and return a list of orphaned instances."""
    ctxt = context.get_admin_context(read_deleted="only")

    orphaned_instances = []

    for vm_ref, vm_rec in _get_applicable_vm_recs(xenapi):
        try:
            uuid = vm_rec['other_config']['nova_uuid']
            instance = db.api.instance_get_by_uuid(ctxt, uuid)
        except (KeyError, exception.InstanceNotFound):
            # NOTE(jk0): Err on the side of caution here. If we don't know
            # anything about the particular instance, ignore it.
            print_xen_object("INFO: Ignoring VM", vm_rec, indent_level=0)
            continue

        # NOTE(jk0): This would be triggered if a VM was deleted but the
        # actual deletion process failed somewhere along the line.
        is_active_and_deleting = (instance.vm_state == "active" and
github openstack / nova / nova / virt / libvirt / host.py View on Github external
def get_connection(self):
        """Returns a connection to the hypervisor

        This method should be used to create and return a well
        configured connection to the hypervisor.

        :returns: a libvirt.virConnect object
        """
        try:
            conn = self._get_connection()
        except libvirt.libvirtError as ex:
            LOG.exception(_("Connection to libvirt failed: %s"), ex)
            payload = dict(ip=CONF.my_ip,
                           method='_connect',
                           reason=ex)
            ctxt = nova_context.get_admin_context()
            rpc.get_notifier('compute').error(ctxt,
                                              'compute.libvirt.error',
                                              payload)
            compute_utils.notify_about_libvirt_connect_error(
                ctxt, ip=CONF.my_ip, exception=ex, tb=traceback.format_exc())
            raise exception.HypervisorUnavailable(host=CONF.host)

        return conn
github openstack / nova / nova / api / openstack / compute / simple_tenant_usage.py View on Github external
def _get_instances_all_cells(self, context, period_start, period_stop,
                                 tenant_id, limit, marker):
        all_instances = []
        cells = objects.CellMappingList.get_all(context)
        for cell in cells:
            with nova_context.target_cell(context, cell) as cctxt:
                try:
                    instances = (
                        objects.InstanceList.get_active_by_window_joined(
                            cctxt, period_start, period_stop, tenant_id,
                            expected_attrs=['flavor'], limit=limit,
                            marker=marker))
                except exception.MarkerNotFound:
                    # NOTE(danms): We need to keep looking through the later
                    # cells to find the marker
                    continue
                all_instances.extend(instances)
                # NOTE(danms): We must have found a marker if we had one,
                # so make sure we don't require a marker in the next cell
                marker = None
                if limit:
                    limit -= len(instances)
github openstack / nova / nova / objects / service.py View on Github external
action='get_minimum_version_all_cells',
            reason='Invalid binary prefix')

    # NOTE(danms): Instead of using Service.get_minimum_version_multi(), we
    # replicate the call directly to the underlying DB method here because
    # we want to defeat the caching and we need to filter non-present
    # services differently from the single-cell method.

    results = nova_context.scatter_gather_all_cells(
        context,
        Service._db_service_get_minimum_version,
        binaries)

    min_version = None
    for cell_uuid, result in results.items():
        if result is nova_context.did_not_respond_sentinel:
            LOG.warning('Cell %s did not respond when getting minimum '
                        'service version', cell_uuid)
            if require_all:
                raise exception.CellTimeout()
        elif isinstance(result, Exception):
            LOG.warning('Failed to get minimum service version for cell %s',
                        cell_uuid)
            if require_all:
                # NOTE(danms): Okay, this isn't necessarily a timeout, but
                # it's functionally the same from the caller's perspective
                # and we logged the fact that it was actually a failure
                # for the forensic investigator during the scatter/gather
                # routine.
                raise exception.CellTimeout()
        else:
            # NOTE(danms): Don't consider a zero or None result as the minimum
github openstack / nova / nova / conductor / manager.py View on Github external
def try_target_cell(context, cell):
    """If cell is not None call func with context.target_cell.

    This is a method to help during the transition period. Currently
    various mappings may not exist if a deployment has not migrated to
    cellsv2. If there is no mapping call the func as normal, otherwise
    call it in a target_cell context.
    """
    if cell:
        with nova_context.target_cell(context, cell) as cell_context:
            yield cell_context
    else:
        yield context
github openstack / nova / nova / api / openstack / auth.py View on Github external
def _authorize_user(self, username, key, req):
        """Generates a new token and assigns it to a user.

        username - string
        key - string API key
        req - wsgi.Request object
        """
        ctxt = context.get_admin_context()

        try:
            user = self.auth.get_user_from_access_key(key)
        except exception.NotFound:
            LOG.warn(_("User not found with provided API key."))
            user = None

        if user and user.name == username:
            token_hash = hashlib.sha1('%s%s%f' % (username, key,
                time.time())).hexdigest()
            token_dict = {}
            token_dict['token_hash'] = token_hash
            token_dict['cdn_management_url'] = ''
            os_url = req.url
            token_dict['server_management_url'] = os_url
            token_dict['storage_url'] = ''
github openstack / nova / nova / objects / service.py View on Github external
services.
    """

    if not all(binary.startswith('nova-') for binary in binaries):
        LOG.warning('get_minimum_version_all_cells called with '
                    'likely-incorrect binaries `%s\'', ','.join(binaries))
        raise exception.ObjectActionError(
            action='get_minimum_version_all_cells',
            reason='Invalid binary prefix')

    # NOTE(danms): Instead of using Service.get_minimum_version_multi(), we
    # replicate the call directly to the underlying DB method here because
    # we want to defeat the caching and we need to filter non-present
    # services differently from the single-cell method.

    results = nova_context.scatter_gather_all_cells(
        context,
        Service._db_service_get_minimum_version,
        binaries)

    min_version = None
    for cell_uuid, result in results.items():
        if result is nova_context.did_not_respond_sentinel:
            LOG.warning('Cell %s did not respond when getting minimum '
                        'service version', cell_uuid)
            if require_all:
                raise exception.CellTimeout()
        elif isinstance(result, Exception):
            LOG.warning('Failed to get minimum service version for cell %s',
                        cell_uuid)
            if require_all:
                # NOTE(danms): Okay, this isn't necessarily a timeout, but