desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Attach a volume to an instance at boot time. So actual attach is done by instance creation'
def _attach_volume_boot(self, context, instance, volume, mountpoint):
instance_id = instance['id'] instance_uuid = instance['uuid'] volume_id = volume['id'] context = context.elevated() LOG.audit(_('Booting with volume %(volume_id)s at %(mountpoint)s'), locals(), context=context, instance=instance) connector = self.driver.get_volume_connector(instan...
'Attach a volume to an instance.'
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id()) @reverts_task_state @wrap_instance_fault def attach_volume(self, context, volume_id, mountpoint, instance):
try: return self._attach_volume(context, volume_id, mountpoint, instance) except Exception: with excutils.save_and_reraise_exception(): capi = self.conductor_api capi.block_device_mapping_destroy_by_instance_and_device(context, instance, mountpoint)
'Do the actual driver detach using block device mapping.'
def _detach_volume(self, context, instance, bdm):
mp = bdm['device_name'] volume_id = bdm['volume_id'] LOG.audit(_('Detach volume %(volume_id)s from mountpoint %(mp)s'), locals(), context=context, instance=instance) connection_info = jsonutils.loads(bdm['connection_info']) if (connection_info and ('serial' not in connection_info)): ...
'Detach a volume from an instance.'
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id()) @reverts_task_state @wrap_instance_fault def detach_volume(self, context, volume_id, instance):
bdm = self._get_instance_volume_bdm(context, instance, volume_id) if (CONF.volume_usage_poll_interval > 0): vol_stats = [] mp = bdm['device_name'] if ('/dev/' in mp): mp = mp[5:] try: vol_stats = self.driver.block_stats(instance['name'], mp) except...
'Remove a volume connection using the volume api.'
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id()) def remove_volume_connection(self, context, volume_id, instance):
try: bdm = self._get_instance_volume_bdm(context, instance, volume_id) self._detach_volume(context, instance, bdm) volume = self.volume_api.get(context, volume_id) connector = self.driver.get_volume_connector(instance) self.volume_api.terminate_connection(context, volume, con...
'Use hotplug to add an network adapter to an instance.'
def attach_interface(self, context, instance, network_id, port_id, requested_ip=None):
network_info = self.network_api.allocate_port_for_instance(context, instance, port_id, network_id, requested_ip, self.conductor_api) if (len(network_info) != 1): LOG.error((_('allocate_port_for_instance returned %(ports)s ports') % dict(ports=len(network_info)))) raise exception.Interfa...
'Detach an network adapter from an instance.'
def detach_interface(self, context, instance, port_id):
network_info = self.network_api.get_instance_nw_info(context.elevated(), instance, conductor_api=self.conductor_api) legacy_nwinfo = self._legacy_nw_info(network_info) condemned = None for (network, mapping) in legacy_nwinfo: if (mapping['vif_uuid'] == port_id): condemned = (network,...
'Check if it is possible to execute live migration. This runs checks on the destination host, and then calls back to the source host to check the results. :param context: security context :param instance: dict of instance data :param block_migration: if true, prepare for block migration :param disk_over_commit: if true...
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id()) def check_can_live_migrate_destination(self, ctxt, instance, block_migration=False, disk_over_commit=False):
src_compute_info = self._get_compute_info(ctxt, instance['host']) dst_compute_info = self._get_compute_info(ctxt, CONF.host) dest_check_data = self.driver.check_can_live_migrate_destination(ctxt, instance, src_compute_info, dst_compute_info, block_migration, disk_over_commit) migrate_data = {} try: ...
'Check if it is possible to execute live migration. This checks if the live migration can succeed, based on the results from check_can_live_migrate_destination. :param context: security context :param instance: dict of instance data :param dest_check_data: result of check_can_live_migrate_destination Returns a dict val...
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id()) def check_can_live_migrate_source(self, ctxt, instance, dest_check_data):
capi = self.conductor_api bdms = capi.block_device_mapping_get_all_by_instance(ctxt, instance) is_volume_backed = self.compute_api.is_volume_backed_instance(ctxt, instance, bdms) dest_check_data['is_volume_backed'] = is_volume_backed return self.driver.check_can_live_migrate_source(ctxt, instance, d...
'Preparations for live migration at dest host. :param context: security context :param instance: dict of instance data :param block_migration: if true, prepare for block migration :param migrate_data : if not None, it is a dict which holds data required for live migration without shared storage.'
def pre_live_migration(self, context, instance, block_migration=False, disk=None, migrate_data=None):
bdms = self._refresh_block_device_connection_info(context, instance) block_device_info = self._get_instance_volume_block_device_info(context, instance, bdms=bdms) network_info = self._get_instance_nw_info(context, instance) fixed_ips = network_info.fixed_ips() if (not fixed_ips): raise excep...
'Executing live migration. :param context: security context :param instance: instance dict :param dest: destination host :param block_migration: if true, prepare for block migration :param migrate_data: implementation specific params'
def live_migration(self, context, dest, instance, block_migration=False, migrate_data=None):
try: if block_migration: disk = self.driver.get_instance_disk_info(instance['name']) else: disk = None self.compute_rpcapi.pre_live_migration(context, instance, block_migration, disk, dest, migrate_data) except Exception: with excutils.save_and_reraise_exc...
'Post operations for live migration. This method is called from live_migration and mainly updating database record. :param ctxt: security context :param instance_ref: nova.db.sqlalchemy.models.Instance :param dest: destination host :param block_migration: if true, prepare for block migration :param migrate_data: if not...
def _post_live_migration(self, ctxt, instance_ref, dest, block_migration=False, migrate_data=None):
LOG.info(_('_post_live_migration() is started..'), instance=instance_ref) connector = self.driver.get_volume_connector(instance_ref) for bdm in self._get_instance_volume_bdms(ctxt, instance_ref): volume = self.volume_api.get(ctxt, bdm['volume_id']) self.volume_api.terminate_connection(...
'Post operations for live migration . :param context: security context :param instance: Instance dict :param block_migration: if true, prepare for block migration'
def post_live_migration_at_destination(self, context, instance, block_migration=False):
LOG.info(_('Post operation of migration started'), instance=instance) self.network_api.setup_networks_on_host(context, instance, self.host) migration = {'source_compute': instance['host'], 'dest_compute': self.host} self.conductor_api.network_migrate_instance_finish(context, instance, migrat...
'Recovers Instance/volume state from migrating -> running. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance :param dest: This method is called from live migration src host. This param specifies destination host. :param block_migration: if true, prepare for block migration :param migr...
def _rollback_live_migration(self, context, instance, dest, block_migration, migrate_data=None):
host = instance['host'] instance = self._instance_update(context, instance['uuid'], host=host, vm_state=vm_states.ACTIVE, task_state=None, expected_task_state=task_states.MIGRATING) self.network_api.setup_networks_on_host(context, instance, self.host) for bdm in self._get_instance_volume_bdms(context, i...
'Cleaning up image directory that is created pre_live_migration. :param context: security context :param instance: an Instance dict sent over rpc'
def rollback_live_migration_at_destination(self, context, instance):
network_info = self._get_instance_nw_info(context, instance) self.network_api.setup_networks_on_host(context, instance, self.host, teardown=True) block_device_info = self._get_instance_volume_block_device_info(context, instance) self.driver.destroy(instance, self._legacy_nw_info(network_info), block_dev...
'Called periodically. On every call, try to update the info_cache\'s network information for another instance by calling to the network manager. This is implemented by keeping a cache of uuids of instances that live on this host. On each call, we pop one off of a list, pull the DB record, and try the call to the netw...
@manager.periodic_task def _heal_instance_info_cache(self, context):
heal_interval = CONF.heal_instance_info_cache_interval if (not heal_interval): return curr_time = time.time() if ((self._last_info_cache_heal + heal_interval) > curr_time): return self._last_info_cache_heal = curr_time instance_uuids = getattr(self, '_instance_uuids_to_heal', Non...
'Return all block device mappings on a compute host.'
def _get_host_volume_bdms(self, context, host):
compute_host_bdms = [] instances = self.conductor_api.instance_get_all_by_host(context, self.host) for instance in instances: instance_bdms = self._get_instance_volume_bdms(context, instance) compute_host_bdms.append(dict(instance=instance, instance_bdms=instance_bdms)) return compute_ho...
'Updates the volume usage cache table with a list of stats.'
def _update_volume_usage_cache(self, context, vol_usages, refreshed):
for usage in vol_usages: greenthread.sleep(0) self.conductor_api.vol_usage_update(context, usage['volume'], usage['rd_req'], usage['rd_bytes'], usage['wr_req'], usage['wr_bytes'], usage['instance'], last_refreshed=refreshed)
'Queries vol usage cache table and sends a vol usage notification.'
def _send_volume_usage_notifications(self, context, start_time):
vol_usages = self.conductor_api.vol_get_usage_by_time(context, start_time) for vol_usage in vol_usages: notifier.notify(context, ('volume.%s' % self.host), 'volume.usage', notifier.INFO, compute_utils.usage_volume_info(vol_usage))
'Align power states between the database and the hypervisor. To sync power state data we make a DB call to get the number of virtual machines known by the hypervisor and if the number matches the number of virtual machines known by the database, we proceed in a lazy loop, one database record at a time, checking if the ...
@manager.periodic_task(spacing=600.0, run_immediately=True) def _sync_power_states(self, context):
db_instances = self.conductor_api.instance_get_all_by_host(context, self.host) num_vm_instances = self.driver.get_num_instances() num_db_instances = len(db_instances) if (num_vm_instances != num_db_instances): LOG.warn((_('Found %(num_db_instances)s in the database and %(num_vm...
'Align instance power state between the database and hypervisor. If the instance is not found on the hypervisor, but is in the database, then a stop() API will be called on the instance.'
def _sync_instance_power_state(self, context, db_instance, vm_power_state):
u = self.conductor_api.instance_get_by_uuid(context, db_instance['uuid']) db_power_state = u['power_state'] vm_state = u['vm_state'] if (self.host != u['host']): LOG.info((_('During the sync_power process the instance has moved from host %(src)s to host %(d...
'Reclaim instances that are queued for deletion.'
@manager.periodic_task def _reclaim_queued_deletes(self, context):
interval = CONF.reclaim_instance_interval if (interval <= 0): LOG.debug(_('CONF.reclaim_instance_interval <= 0, skipping...')) return instances = self.conductor_api.instance_get_all_by_host(context, self.host) for instance in instances: old_enough = ((not instance['delet...
'See driver.get_available_resource() Periodic process that keeps that the compute host\'s understanding of resource availability and usage in sync with the underlying hypervisor. :param context: security context'
@manager.periodic_task def update_available_resource(self, context):
new_resource_tracker_dict = {} nodenames = set(self.driver.get_available_nodes()) for nodename in nodenames: rt = self._get_resource_tracker(nodename) rt.update_available_resource(context) new_resource_tracker_dict[nodename] = rt compute_nodes_in_db = self._get_compute_nodes_in_d...
'Cleanup any instances which are erroneously still running after having been deleted. Valid actions to take are: 1. noop - do nothing 2. log - log which instances are erroneously running 3. reap - shutdown and cleanup any erroneously running instances The use-case for this cleanup task is: for various reasons, it may b...
@manager.periodic_task(spacing=CONF.running_deleted_instance_poll_interval) def _cleanup_running_deleted_instances(self, context):
action = CONF.running_deleted_instance_action if (action == 'noop'): return with utils.temporary_mutation(context, read_deleted='yes'): for instance in self._running_deleted_instances(context): capi = self.conductor_api bdms = capi.block_device_mapping_get_all_by_inst...
'Returns a list of instances nova thinks is deleted, but the hypervisor thinks is still running.'
def _running_deleted_instances(self, context):
timeout = CONF.running_deleted_instance_timeout def deleted_instance(instance): erroneously_running = instance['deleted'] old_enough = ((not instance['deleted_at']) or timeutils.is_older_than(instance['deleted_at'], timeout)) if (erroneously_running and old_enough): return Tr...
'Notify hypervisor of change (for hypervisor pools).'
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id()) def add_aggregate_host(self, context, host, slave_info=None, aggregate=None, aggregate_id=None):
if (not aggregate): aggregate = self.conductor_api.aggregate_get(context, aggregate_id) try: self.driver.add_to_aggregate(context, aggregate, host, slave_info=slave_info) except exception.AggregateError: with excutils.save_and_reraise_exception(): self.driver.undo_aggrega...
'Removes a host from a physical hypervisor pool.'
@exception.wrap_exception(notifier=notifier, publisher_id=publisher_id()) def remove_aggregate_host(self, context, host, slave_info=None, aggregate=None, aggregate_id=None):
if (not aggregate): aggregate = self.conductor_api.aggregate_get(context, aggregate_id) try: self.driver.remove_from_aggregate(context, aggregate, host, slave_info=slave_info) except (exception.AggregateError, exception.InvalidAggregateAction) as e: with excutils.save_and_reraise_exc...
'Run a single pass of the image cache manager.'
@manager.periodic_task(spacing=CONF.image_cache_manager_interval, external_process_ok=True) def _run_image_cache_manager_pass(self, context):
if (not self.driver.capabilities['has_imagecache']): return if (CONF.image_cache_manager_interval == 0): return all_instances = self.conductor_api.instance_get_all(context) storage_users.register_storage_use(CONF.instances_path, CONF.host) nodes = storage_users.get_storage_users(CONF...
'Update an instance in the database using kwargs as value.'
def _instance_update(self, context, instance_uuid, **kwargs):
(old_ref, instance_ref) = self.db.instance_update_and_get_original(context, instance_uuid, kwargs) notifications.send_update(context, old_ref, instance_ref, 'api') return instance_ref
'Enforce quota limits on injected files. Raises a QuotaError if any limit is exceeded.'
def _check_injected_file_quota(self, context, injected_files):
if (injected_files is None): return try: QUOTAS.limit_check(context, injected_files=len(injected_files)) except exception.OverQuota: raise exception.OnsetFileLimitExceeded() max_path = 0 max_content = 0 for (path, content) in injected_files: max_path = max(max_pat...
'Enforce quota limits on number of instances created.'
def _check_num_instances_quota(self, context, instance_type, min_count, max_count):
req_cores = (max_count * instance_type['vcpus']) req_ram = (max_count * instance_type['memory_mb']) try: reservations = QUOTAS.reserve(context, instances=max_count, cores=req_cores, ram=req_ram) except exception.OverQuota as exc: quotas = exc.kwargs['quotas'] usages = exc.kwargs[...
'Enforce quota limits on metadata properties.'
def _check_metadata_properties_quota(self, context, metadata=None):
if (not metadata): metadata = {} num_metadata = len(metadata) try: QUOTAS.limit_check(context, metadata_items=num_metadata) except exception.OverQuota as exc: pid = context.project_id LOG.warn((_('Quota exceeded for %(pid)s, tried to set %(num_metadat...
'Check if the security group requested exists and belongs to the project.'
def _check_requested_secgroups(self, context, secgroups):
for secgroup in secgroups: if (secgroup == 'default'): continue if (not self.security_group_api.get(context, secgroup)): raise exception.SecurityGroupNotFoundForProject(project_id=context.project_id, security_group_id=secgroup)
'Check if the networks requested belongs to the project and the fixed IP address for each network provided is within same the network block'
def _check_requested_networks(self, context, requested_networks):
if (not requested_networks): return self.network_api.validate_networks(context, requested_networks)
'Choose kernel and ramdisk appropriate for the instance. The kernel and ramdisk can be chosen in one of three ways: 1. Passed in with create-instance request. 2. Inherited from image. 3. Forced to None by using `null_kernel` FLAG.'
@staticmethod def _handle_kernel_and_ramdisk(context, kernel_id, ramdisk_id, image):
image_properties = image.get('properties', {}) if (kernel_id is None): kernel_id = image_properties.get('kernel_id') if (ramdisk_id is None): ramdisk_id = image_properties.get('ramdisk_id') if (kernel_id == str(CONF.null_kernel)): kernel_id = None ramdisk_id = None if...
'Verify all the input parameters regardless of the provisioning strategy being performed.'
def _validate_and_provision_instance(self, context, instance_type, image_href, kernel_id, ramdisk_id, min_count, max_count, display_name, display_description, key_name, key_data, security_groups, availability_zone, user_data, metadata, injected_files, access_ip_v4, access_ip_v6, requested_networks, config_drive, block_...
if (not metadata): metadata = {} if (not security_groups): security_groups = ['default'] if (not instance_type): instance_type = instance_types.get_default_instance_type() if (not min_count): min_count = 1 if (not max_count): max_count = min_count block_de...
'Verify all the input parameters regardless of the provisioning strategy being performed and schedule the instance(s) for creation.'
def _create_instance(self, context, instance_type, image_href, kernel_id, ramdisk_id, min_count, max_count, display_name, display_description, key_name, key_data, security_group, availability_zone, user_data, metadata, injected_files, admin_password, access_ip_v4, access_ip_v6, requested_networks, config_drive, block_d...
if (reservation_id is None): reservation_id = utils.generate_uid('r') (instances, request_spec, filter_properties) = self._validate_and_provision_instance(context, instance_type, image_href, kernel_id, ramdisk_id, min_count, max_count, display_name, display_description, key_name, key_data, security_grou...
'tell vm driver to create ephemeral/swap device at boot time by updating BlockDeviceMapping'
def _update_image_block_device_mapping(self, elevated_context, instance_type, instance_uuid, mappings):
for bdm in block_device.mappings_prepend_dev(mappings): LOG.debug(_('bdm %s'), bdm, instance_uuid=instance_uuid) virtual_name = bdm['virtual'] if ((virtual_name == 'ami') or (virtual_name == 'root')): continue if (not block_device.is_swap_or_ephemeral(virtual_name)): ...
'tell vm driver to attach volume at boot time by updating BlockDeviceMapping'
def _update_block_device_mapping(self, elevated_context, instance_type, instance_uuid, block_device_mapping):
LOG.debug(_('block_device_mapping %s'), block_device_mapping, instance_uuid=instance_uuid) for bdm in block_device_mapping: assert ('device_name' in bdm) values = {'instance_uuid': instance_uuid} for key in ('device_name', 'delete_on_termination', 'virtual_name', 'snapshot_id', 'volum...
'Populate instance block device mapping information.'
def _populate_instance_for_bdm(self, context, instance, instance_type, image, block_device_mapping):
instance_uuid = instance['uuid'] image_properties = image.get('properties', {}) mappings = image_properties.get('mappings', []) if mappings: self._update_image_block_device_mapping(context, instance_type, instance_uuid, mappings) image_bdm = image_properties.get('block_device_mapping', []) ...
'Populate instance shutdown_terminate information.'
def _populate_instance_shutdown_terminate(self, instance, image, block_device_mapping):
image_properties = image.get('properties', {}) if (block_device_mapping or image_properties.get('mappings') or image_properties.get('block_device_mapping')): instance['shutdown_terminate'] = False
'Populate instance display_name and hostname.'
def _populate_instance_names(self, instance, num_instances):
display_name = instance.get('display_name') hostname = instance.get('hostname') if (display_name is None): display_name = self._default_display_name(instance['uuid']) instance['display_name'] = display_name if ((hostname is None) and (num_instances == 1)): hostname = display_name...
'Build the beginning of a new instance.'
def _populate_instance_for_create(self, base_options, image, security_groups):
image_properties = image.get('properties', {}) instance = base_options if (not instance.get('uuid')): instance['uuid'] = str(uuid.uuid4()) instance['launch_index'] = 0 instance['vm_state'] = vm_states.BUILDING instance['task_state'] = task_states.SCHEDULING instance['info_cache'] = {...
'Create an entry in the DB for this new instance, including any related table updates (such as security group, etc). This is called by the scheduler after a location for the instance has been determined.'
def create_db_entry_for_new_instance(self, context, instance_type, image, base_options, security_group, block_device_mapping, num_instances, index):
instance = self._populate_instance_for_create(base_options, image, security_group) self._populate_instance_names(instance, num_instances) self._populate_instance_shutdown_terminate(instance, image, block_device_mapping) self.security_group_api.ensure_default(context) instance = self.db.instance_crea...
'Check policies for create().'
def _check_create_policies(self, context, availability_zone, requested_networks, block_device_mapping):
target = {'project_id': context.project_id, 'user_id': context.user_id, 'availability_zone': availability_zone} check_policy(context, 'create', target) if requested_networks: check_policy(context, 'create:attach_network', target) if block_device_mapping: check_policy(context, 'create:att...
'Provision instances, sending instance information to the scheduler. The scheduler will determine where the instance(s) go and will handle creating the DB entries. Returns a tuple of (instances, reservation_id)'
@hooks.add_hook('create_instance') def create(self, context, instance_type, image_href, kernel_id=None, ramdisk_id=None, min_count=None, max_count=None, display_name=None, display_description=None, key_name=None, key_data=None, security_group=None, availability_zone=None, user_data=None, metadata=None, injected_files=N...
self._check_create_policies(context, availability_zone, requested_networks, block_device_mapping) return self._create_instance(context, instance_type, image_href, kernel_id, ramdisk_id, min_count, max_count, display_name, display_description, key_name, key_data, security_group, availability_zone, user_data, met...
'Called when a rule is added/removed from a provider firewall.'
def trigger_provider_fw_rules_refresh(self, context):
for service in self.db.service_get_all_by_topic(context, CONF.compute_topic): host_name = service['host'] self.compute_rpcapi.refresh_provider_fw_rules(context, host_name)
'Updates the state of a compute instance. For example to \'active\' or \'error\'. Also sets \'task_state\' to None. Used by admin_actions api :param context: The security context :param instance: The instance to update :param new_state: A member of vm_state, eg. \'active\''
def update_state(self, context, instance, new_state):
self.update(context, instance, vm_state=new_state, task_state=None)
'Updates the instance in the datastore. :param context: The security context :param instance: The instance to update :param kwargs: All additional keyword args are treated as data fields of the instance to be updated :returns: None'
@wrap_check_policy def update(self, context, instance, **kwargs):
(_, updated) = self._update(context, instance, **kwargs) return updated
'Terminate an instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=None, task_state=None) def soft_delete(self, context, instance):
LOG.debug(_('Going to try to soft delete instance'), instance=instance) def soft_delete(context, instance, bdms, reservations=None): self.compute_rpcapi.soft_delete_instance(context, instance, reservations=reservations) self._delete(context, instance, soft_delete, task_state=task_s...
'Terminate an instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=None, task_state=None) def delete(self, context, instance):
LOG.debug(_('Going to try to terminate instance'), instance=instance) self._delete_instance(context, instance)
'Restore a previously deleted (but not reclaimed) instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.SOFT_DELETED]) def restore(self, context, instance):
instance_type = instance_types.extract_instance_type(instance) (num_instances, quota_reservations) = self._check_num_instances_quota(context, instance_type, 1, 1) self._record_action_start(context, instance, instance_actions.RESTORE) try: if instance['host']: instance = self.update(c...
'Force delete a previously deleted (but not reclaimed) instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.SOFT_DELETED]) def force_delete(self, context, instance):
self._delete_instance(context, instance)
'Stop an instance.'
@wrap_check_policy @check_instance_lock @check_instance_host @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.RESCUED, vm_states.ERROR, vm_states.STOPPED], task_state=[None]) def stop(self, context, instance, do_cast=True):
LOG.debug(_('Going to try to stop instance'), instance=instance) instance = self.update(context, instance, task_state=task_states.POWERING_OFF, expected_task_state=None, progress=0) self._record_action_start(context, instance, instance_actions.STOP) self.compute_rpcapi.stop_instance(conte...
'Start an instance.'
@wrap_check_policy @check_instance_lock @check_instance_host @check_instance_state(vm_state=[vm_states.STOPPED]) def start(self, context, instance):
LOG.debug(_('Going to try to start instance'), instance=instance) instance = self.update(context, instance, task_state=task_states.POWERING_ON, expected_task_state=None) self._record_action_start(context, instance, instance_actions.START) self.compute_rpcapi.start_instance(context, instan...
'Get instances that were continuously active over a window.'
def get_active_by_window(self, context, begin, end=None, project_id=None):
return self.db.instance_get_active_by_window_joined(context, begin, end, project_id)
'Get an instance type by instance type id.'
def get_instance_type(self, context, instance_type_id):
return instance_types.get_instance_type(instance_type_id)
'Get a single instance with the given instance_id.'
def get(self, context, instance_id):
try: if uuidutils.is_uuid_like(instance_id): instance = self.db.instance_get_by_uuid(context, instance_id) elif utils.is_int_like(instance_id): instance = self.db.instance_get(context, instance_id) else: raise exception.InstanceNotFound(instance_id=instanc...
'Get all instances filtered by one of the given parameters. If there is no filter and the context is an admin, it will retrieve all instances in the system. Deleted instances will be returned by default, unless there is a search option that says otherwise. The results will be returned sorted in the order specified by t...
def get_all(self, context, search_opts=None, sort_key='created_at', sort_dir='desc', limit=None, marker=None):
target = {'project_id': context.project_id, 'user_id': context.user_id} check_policy(context, 'get_all', target) if (search_opts is None): search_opts = {} if ('all_tenants' in search_opts): check_policy(context, 'get_all_tenants', target) LOG.debug((_('Searching by: %s') % str...
'Backup the given instance :param instance: nova.db.sqlalchemy.models.Instance :param name: name of the backup or snapshot name = backup_type # daily backups are called \'daily\' :param rotation: int representing how many backups to keep around; None if rotation shouldn\'t be used (as in the case of snapshots) :param ...
@wrap_check_policy @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED]) def backup(self, context, instance, name, backup_type, rotation, extra_properties=None, image_id=None):
if image_id: image_meta = self.image_service.show(context, image_id) else: image_meta = self._create_image(context, instance, name, 'backup', backup_type=backup_type, rotation=rotation, extra_properties=extra_properties) instance = self.update(context, instance, task_state=task_states.IMAGE_...
'Snapshot the given instance. :param instance: nova.db.sqlalchemy.models.Instance :param name: name of the backup or snapshot :param extra_properties: dict of extra image properties to include :returns: A dict containing image metadata'
@wrap_check_policy @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED, vm_states.PAUSED, vm_states.SUSPENDED]) def snapshot(self, context, instance, name, extra_properties=None, image_id=None):
if image_id: image_meta = self.image_service.show(context, image_id) else: image_meta = self._create_image(context, instance, name, 'snapshot', extra_properties=extra_properties) instance = self.update(context, instance, task_state=task_states.IMAGE_SNAPSHOT, expected_task_state=None) se...
'Create new image entry in the image service. This new image will be reserved for the compute manager to upload a snapshot or backup. :param context: security context :param instance: nova.db.sqlalchemy.models.Instance :param name: string for name of the snapshot :param image_type: snapshot | backup :param backup_type...
def _create_image(self, context, instance, name, image_type, backup_type=None, rotation=None, extra_properties=None):
instance_uuid = instance['uuid'] properties = {'instance_uuid': instance_uuid, 'user_id': str(context.user_id), 'image_type': image_type} sent_meta = {'name': name, 'is_public': False, 'properties': properties} system_meta = self.db.instance_system_metadata_get(context, instance_uuid) base_image_ref...
'Snapshot the given volume-backed instance. :param instance: nova.db.sqlalchemy.models.Instance :param image_meta: metadata for the new image :param name: name of the backup or snapshot :param extra_properties: dict of extra image properties to include :returns: the new image metadata'
@check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED]) def snapshot_volume_backed(self, context, instance, image_meta, name, extra_properties=None):
image_meta['name'] = name properties = image_meta['properties'] if instance['root_device_name']: properties['root_device_name'] = instance['root_device_name'] properties.update((extra_properties or {})) bdms = self.get_instance_bdms(context, instance) mapping = [] for bdm in bdms: ...
'Reboot the given instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED, vm_states.PAUSED, vm_states.SUSPENDED], task_state=[None, task_states.REBOOTING, task_states.REBOOTING_HARD, task_states.RESUMING, task_states.UNPAUSING, task_states.PAUSING, task_states.SUSPENDING]) def reboot(...
if ((reboot_type == 'SOFT') and (instance['task_state'] == task_states.REBOOTING)): raise exception.InstanceInvalidState(attr='task_state', instance_uuid=instance['uuid'], state=instance['task_state'], method='reboot') state = {'SOFT': task_states.REBOOTING, 'HARD': task_states.REBOOTING_HARD}[reboot_ty...
'Throws an ImageNotFound exception if image_href does not exist.'
def _get_image(self, context, image_href):
(image_service, image_id) = glance.get_remote_image_service(context, image_href) return image_service.show(context, image_id)
'Rebuild the given instance with the provided attributes.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED], task_state=[None]) def rebuild(self, context, instance, image_href, admin_password, **kwargs):
if instance['image_ref']: orig_image_ref = instance['image_ref'] image = self._get_image(context, image_href) else: orig_image_ref = '' image = {} files_to_inject = kwargs.pop('files_to_inject', []) self._check_injected_file_quota(context, files_to_inject) metadata = ...
'Reverts a resize, deleting the \'new\' instance in the process.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.RESIZED]) def revert_resize(self, context, instance):
elevated = context.elevated() migration_ref = self.db.migration_get_by_instance_and_status(elevated, instance['uuid'], 'finished') deltas = self._reverse_upsize_quota_delta(context, migration_ref) reservations = self._reserve_quota_delta(context, deltas) instance = self.update(context, instance, tas...
'Confirms a migration/resize and deletes the \'old\' instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.RESIZED]) def confirm_resize(self, context, instance, migration_ref=None):
elevated = context.elevated() if (migration_ref is None): migration_ref = self.db.migration_get_by_instance_and_status(elevated, instance['uuid'], 'finished') deltas = self._downsize_quota_delta(context, instance) reservations = self._reserve_quota_delta(context, deltas) instance = self.upda...
'Calculate any quota adjustment required at a particular point in the resize cycle. :param context: the request context :param new_instance_type: the target instance type :param old_instance_type: the original instance type :param sense: the sense of the adjustment, 1 indicates a forward adjustment, whereas -1 indicate...
@staticmethod def _resize_quota_delta(context, new_instance_type, old_instance_type, sense, compare):
def _quota_delta(resource): return (sense * (new_instance_type[resource] - old_instance_type[resource])) deltas = {} if ((compare * _quota_delta('vcpus')) > 0): deltas['cores'] = _quota_delta('vcpus') if ((compare * _quota_delta('memory_mb')) > 0): deltas['ram'] = _quota_delta('m...
'Calculate deltas required to adjust quota for an instance upsize.'
@staticmethod def _upsize_quota_delta(context, new_instance_type, old_instance_type):
return API._resize_quota_delta(context, new_instance_type, old_instance_type, 1, 1)
'Calculate deltas required to reverse a prior upsizing quota adjustment.'
@staticmethod def _reverse_upsize_quota_delta(context, migration_ref):
old_instance_type = instance_types.get_instance_type(migration_ref['old_instance_type_id']) new_instance_type = instance_types.get_instance_type(migration_ref['new_instance_type_id']) return API._resize_quota_delta(context, new_instance_type, old_instance_type, (-1), (-1))
'Calculate deltas required to adjust quota for an instance downsize.'
@staticmethod def _downsize_quota_delta(context, instance):
old_instance_type = instance_types.extract_instance_type(instance, 'old_') new_instance_type = instance_types.extract_instance_type(instance, 'new_') return API._resize_quota_delta(context, new_instance_type, old_instance_type, 1, (-1))
'Resize (ie, migrate) a running instance. If flavor_id is None, the process is considered a migration, keeping the original flavor_id. If flavor_id is not None, the instance should be migrated to a new host and resized to the new flavor_id.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED], task_state=[None]) def resize(self, context, instance, flavor_id=None, **kwargs):
current_instance_type = instance_types.extract_instance_type(instance) if (not flavor_id): LOG.debug(_('flavor_id is None. Assuming migration.'), instance=instance) new_instance_type = current_instance_type else: new_instance_type = instance_types.get_instance_type_by_fla...
'Add fixed_ip from specified network to given instance.'
@wrap_check_policy @check_instance_lock def add_fixed_ip(self, context, instance, network_id):
self.compute_rpcapi.add_fixed_ip_to_instance(context, instance=instance, network_id=network_id)
'Remove fixed_ip from specified network to given instance.'
@wrap_check_policy @check_instance_lock def remove_fixed_ip(self, context, instance, address):
self.compute_rpcapi.remove_fixed_ip_from_instance(context, instance=instance, address=address)
'Pause the given instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.RESCUED]) def pause(self, context, instance):
self.update(context, instance, vm_state=vm_states.ACTIVE, task_state=task_states.PAUSING, expected_task_state=None) self._record_action_start(context, instance, instance_actions.PAUSE) self.compute_rpcapi.pause_instance(context, instance=instance)
'Unpause the given instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.PAUSED]) def unpause(self, context, instance):
self.update(context, instance, vm_state=vm_states.PAUSED, task_state=task_states.UNPAUSING, expected_task_state=None) self._record_action_start(context, instance, instance_actions.UNPAUSE) self.compute_rpcapi.unpause_instance(context, instance=instance)
'Retrieve diagnostics for the given instance.'
@wrap_check_policy def get_diagnostics(self, context, instance):
return self.compute_rpcapi.get_diagnostics(context, instance=instance)
'Retrieve backdoor port.'
def get_backdoor_port(self, context, host_name):
return self.compute_rpcapi.get_backdoor_port(context, host_name)
'Suspend the given instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.RESCUED]) def suspend(self, context, instance):
self.update(context, instance, vm_state=vm_states.ACTIVE, task_state=task_states.SUSPENDING, expected_task_state=None) self._record_action_start(context, instance, instance_actions.SUSPEND) self.compute_rpcapi.suspend_instance(context, instance=instance)
'Resume the given instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.SUSPENDED]) def resume(self, context, instance):
self.update(context, instance, vm_state=vm_states.SUSPENDED, task_state=task_states.RESUMING, expected_task_state=None) self._record_action_start(context, instance, instance_actions.RESUME) self.compute_rpcapi.resume_instance(context, instance=instance)
'Rescue the given instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.STOPPED]) def rescue(self, context, instance, rescue_password=None):
if self.is_volume_backed_instance(context, instance, None): reason = _('Cannot rescue a volume-backed instance') raise exception.InstanceNotRescuable(instance_id=instance['uuid'], reason=reason) self.update(context, instance, vm_state=vm_states.ACTIVE, task_state=task_states.RESCUING...
'Unrescue the given instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.RESCUED]) def unrescue(self, context, instance):
self.update(context, instance, vm_state=vm_states.RESCUED, task_state=task_states.UNRESCUING, expected_task_state=None) self._record_action_start(context, instance, instance_actions.UNRESCUE) self.compute_rpcapi.unrescue_instance(context, instance=instance)
'Set the root/admin password for the given instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.ACTIVE]) def set_admin_password(self, context, instance, password=None):
self.update(context, instance, task_state=task_states.UPDATING_PASSWORD, expected_task_state=None) self._record_action_start(context, instance, instance_actions.CHANGE_PASSWORD) self.compute_rpcapi.set_admin_password(context, instance=instance, new_pass=password)
'Write a file to the given instance.'
@wrap_check_policy @check_instance_lock def inject_file(self, context, instance, path, file_contents):
self.compute_rpcapi.inject_file(context, instance=instance, path=path, file_contents=file_contents)
'Get a url to an instance Console.'
@wrap_check_policy @check_instance_host def get_vnc_console(self, context, instance, console_type):
connect_info = self.compute_rpcapi.get_vnc_console(context, instance=instance, console_type=console_type) self.consoleauth_rpcapi.authorize_console(context, connect_info['token'], console_type, connect_info['host'], connect_info['port'], connect_info['internal_access_path'], instance['uuid']) return {'url':...
'Used in a child cell to get console info.'
@check_instance_host def get_vnc_connect_info(self, context, instance, console_type):
connect_info = self.compute_rpcapi.get_vnc_console(context, instance=instance, console_type=console_type) return connect_info
'Get a url to an instance Console.'
@wrap_check_policy @check_instance_host def get_spice_console(self, context, instance, console_type):
connect_info = self.compute_rpcapi.get_spice_console(context, instance=instance, console_type=console_type) self.consoleauth_rpcapi.authorize_console(context, connect_info['token'], console_type, connect_info['host'], connect_info['port'], connect_info['internal_access_path'], instance['uuid']) return {'url...
'Used in a child cell to get console info.'
@check_instance_host def get_spice_connect_info(self, context, instance, console_type):
connect_info = self.compute_rpcapi.get_spice_console(context, instance=instance, console_type=console_type) return connect_info
'Get console output for an instance.'
@wrap_check_policy @check_instance_host def get_console_output(self, context, instance, tail_length=None):
return self.compute_rpcapi.get_console_output(context, instance=instance, tail_length=tail_length)
'Lock the given instance.'
@wrap_check_policy def lock(self, context, instance):
context = context.elevated() instance_uuid = instance['uuid'] LOG.debug(_('Locking'), context=context, instance_uuid=instance_uuid) self._instance_update(context, instance_uuid, locked=True)
'Unlock the given instance.'
@wrap_check_policy def unlock(self, context, instance):
context = context.elevated() instance_uuid = instance['uuid'] LOG.debug(_('Unlocking'), context=context, instance_uuid=instance_uuid) self._instance_update(context, instance_uuid, locked=False)
'Return the boolean state of given instance\'s lock.'
@wrap_check_policy def get_lock(self, context, instance):
return self.get(context, instance['uuid'])['locked']
'Reset networking on the instance.'
@wrap_check_policy @check_instance_lock def reset_network(self, context, instance):
self.compute_rpcapi.reset_network(context, instance=instance)
'Inject network info for the instance.'
@wrap_check_policy @check_instance_lock def inject_network_info(self, context, instance):
self.compute_rpcapi.inject_network_info(context, instance=instance)
'Attach an existing volume to an existing instance.'
@wrap_check_policy @check_instance_lock @check_instance_state(vm_state=[vm_states.ACTIVE, vm_states.PAUSED, vm_states.SUSPENDED, vm_states.STOPPED, vm_states.RESIZED, vm_states.SOFT_DELETED], task_state=None) def attach_volume(self, context, instance, volume_id, device=None):
if (device and (not block_device.match_device(device))): raise exception.InvalidDevicePath(path=device) device = self.compute_rpcapi.reserve_block_device_name(context, device=device, instance=instance, volume_id=volume_id) try: volume = self.volume_api.get(context, volume_id) self.vo...
'Detach a volume from an instance.'
def detach_volume(self, context, volume_id):
volume = self.volume_api.get(context, volume_id) if (volume['attach_status'] == 'detached'): msg = _('Volume must be attached in order to detach.') raise exception.InvalidVolume(reason=msg) instance_uuid = volume['instance_uuid'] instance = self.db.instance_get_by_uu...
'Use hotplug to add an network adapter to an instance.'
@wrap_check_policy def attach_interface(self, context, instance, network_id, port_id, requested_ip):
return self.compute_rpcapi.attach_interface(context, instance=instance, network_id=network_id, port_id=port_id, requested_ip=requested_ip)
'Detach an network adapter from an instance.'
@wrap_check_policy def detach_interface(self, context, instance, port_id):
self.compute_rpcapi.detach_interface(context, instance=instance, port_id=port_id)
'Get all metadata associated with an instance.'
@wrap_check_policy def get_instance_metadata(self, context, instance):
rv = self.db.instance_metadata_get(context, instance['uuid']) return dict(rv.iteritems())