def flavor_list_paged(request, is_public=True, get_extras=False, marker=None, paginate=False, sort_key="name", sort_dir="desc", reversed_order=False): """Get the list of available instance sizes (flavors).""" has_more_data = False has_prev_data = False if paginate: if reversed_order: sort_dir = 'desc' if sort_dir == 'asc' else 'asc' page_size = utils.get_page_size(request) flavors = _nova.novaclient(request).flavors.list(is_public=is_public, marker=marker, limit=page_size + 1, sort_key=sort_key, sort_dir=sort_dir) flavors, has_more_data, has_prev_data = update_pagination( flavors, page_size, marker, reversed_order) else: flavors = _nova.novaclient(request).flavors.list(is_public=is_public) if get_extras: for flavor in flavors: flavor.extras = flavor_get_extras(request, flavor.id, True, flavor) return (flavors, has_more_data, has_prev_data)
def server_delete(request, instance_id): _nova.novaclient(request).servers.delete(instance_id) # Session is available and consistent for the current view # among Horizon django servers even in load-balancing setup, # so only the view listing the servers will recognize it as # own DeleteInstance action performed. Note that dict is passed # by reference in python. Quote from django's developer manual: # " You can read it and write to request.session at any point # in your view. You can edit it multiple times." request.session['server_deleted'] = instance_id
def instance_volume_attach(request, volume_id, instance_id, device): # If we have a multiattach volume, we need to use microversion>=2.60. volume = cinder.volume_get(request, volume_id) if volume.multiattach: version = get_microversion(request, 'multiattach') if version: client = _nova.novaclient(request, version) else: raise VolumeMultiattachNotSupported( _('Multiattach volumes are not yet supported.')) else: client = _nova.novaclient(request) return client.volumes.create_server_volume( instance_id, volume_id, device)
def server_create(request, name, image, flavor, key_name, user_data, security_groups, block_device_mapping=None, block_device_mapping_v2=None, nics=None, availability_zone=None, instance_count=1, admin_pass=None, disk_config=None, config_drive=None, meta=None, scheduler_hints=None, description=None): microversion = get_microversion(request, ("instance_description", "auto_allocated_network")) nova_client = _nova.novaclient(request, version=microversion) # NOTE(amotoki): Handling auto allocated network # Nova API 2.37 or later, it accepts a special string 'auto' for nics # which means nova uses a network that is available for a current project # if one exists and otherwise it creates a network automatically. # This special handling is processed here as JS side assumes 'nics' # is a list and it is easiest to handle it here. if nics: is_auto_allocate = any(nic.get('net-id') == '__auto_allocate__' for nic in nics) if is_auto_allocate: nics = 'auto' kwargs = {} if description is not None: kwargs['description'] = description return Server(nova_client.servers.create( name.strip(), image, flavor, userdata=user_data, security_groups=security_groups, key_name=key_name, block_device_mapping=block_device_mapping, block_device_mapping_v2=block_device_mapping_v2, nics=nics, availability_zone=availability_zone, min_count=instance_count, admin_pass=admin_pass, disk_config=disk_config, config_drive=config_drive, meta=meta, scheduler_hints=scheduler_hints, **kwargs), request)
def update(self, request, form=None, **kwargs): self.choices = [('', _('No keypair'))] with helpers.current_region(request, getattr(form, 'region', None)): keypairs = nova.novaclient(request).keypairs.list() for keypair in sorted(keypairs, key=lambda e: e.name): self.choices.append((keypair.name, keypair.name))
def flavor_list(request, is_public=True, get_extras=False): """Get the list of available instance sizes (flavors).""" flavors = _nova.novaclient(request).flavors.list(is_public=is_public) if get_extras: for flavor in flavors: flavor.extras = flavor_get_extras(request, flavor.id, True, flavor) return flavors
def migrate_host(request, host, live_migrate=False, disk_over_commit=False, block_migration=False): nc = _nova.novaclient(request) hypervisors = nc.hypervisors.search(host, True) response = [] err_code = None for hyper in hypervisors: for server in getattr(hyper, "servers", []): try: if live_migrate: instance = server_get(request, server['uuid']) # Checking that instance can be live-migrated if instance.status in ["ACTIVE", "PAUSED"]: nc.servers.live_migrate( server['uuid'], None, block_migration, disk_over_commit ) else: nc.servers.migrate(server['uuid']) else: nc.servers.migrate(server['uuid']) except nova_exceptions.ClientException as err: err_code = err.code msg = _("Name: %(name)s ID: %(uuid)s") msg = msg % {'name': server['name'], 'uuid': server['uuid']} response.append(msg) if err_code: msg = _('Failed to migrate instances: %s') % ', '.join(response) raise nova_exceptions.ClientException(err_code, msg) return True
def upgrade_api(request, client, version): """Ugrade the nova API to the specified version if possible.""" min_ver, max_ver = api_versions._get_server_version_range(client) if min_ver <= api_versions.APIVersion(version) <= max_ver: client = _nova.novaclient(request, version) return client
def instance_volumes_list(request, instance_id): volumes = _nova.novaclient(request).volumes.get_server_volumes(instance_id) for volume in volumes: volume_data = cinder.cinderclient(request).volumes.get(volume.id) volume.name = cinder.Volume(volume_data).name return volumes
def flavor_get_extras(request, flavor_id, raw=False, flavor=None): """Get flavor extra specs.""" if flavor is None: flavor = _nova.novaclient(request).flavors.get(flavor_id) extras = flavor.get_keys() if raw: return extras return [FlavorExtraSpec(flavor_id, key, value) for key, value in extras.items()]
def list_extensions(request): """List all nova extensions, except the ones in the blacklist.""" blacklist = set(settings.OPENSTACK_NOVA_EXTENSIONS_BLACKLIST) nova_api = _nova.novaclient(request) return tuple( extension for extension in nova_list_extensions.ListExtManager(nova_api).show_all() if extension.name not in blacklist )
def flavor_create(request, name, memory, vcpu, disk, flavorid='auto', ephemeral=0, swap=0, metadata=None, is_public=True, rxtx_factor=1): flavor = _nova.novaclient(request).flavors.create(name, memory, vcpu, disk, flavorid=flavorid, ephemeral=ephemeral, swap=swap, is_public=is_public, rxtx_factor=rxtx_factor) if (metadata): flavor_extra_set(request, flavor.id, metadata) return flavor
def usage_get(request, tenant_id, start, end): client = upgrade_api(request, _nova.novaclient(request), '2.40') usage = client.usage.get(tenant_id, start, end) if client.api_version >= api_versions.APIVersion('2.40'): # If the number of instances used to calculate the usage is greater # than max_limit, the usage will be split across multiple requests # and the responses will need to be merged back together. marker = _get_usage_marker(usage) while marker: next_usage = client.usage.get(tenant_id, start, end, marker=marker) marker = _get_usage_marker(next_usage) if marker: _merge_usage(usage, next_usage) return NovaUsage(usage)
def evacuate_host(request, host, target=None, on_shared_storage=False): # TODO(jmolle) This should be change for nova atomic api host_evacuate hypervisors = _nova.novaclient(request).hypervisors.search(host, True) response = [] err_code = None for hypervisor in hypervisors: hyper = Hypervisor(hypervisor) # if hypervisor doesn't have servers, the attribute is not present for server in hyper.servers: try: _nova.novaclient(request).servers.evacuate(server['uuid'], target, on_shared_storage) except nova_exceptions.ClientException as err: err_code = err.code msg = _("Name: %(name)s ID: %(uuid)s") msg = msg % {'name': server['name'], 'uuid': server['uuid']} response.append(msg) if err_code: msg = _('Failed to evacuate instances: %s') % ', '.join(response) raise nova_exceptions.ClientException(err_code, msg) return True
def update(self, request, form=None, **kwargs): choices = [] with helpers.current_region(request, getattr(form, 'region', None)): flavors = nova.novaclient(request).flavors.list() # If no requirements are present, return all the flavors. if not hasattr(self, 'requirements'): choices = [(flavor.id, flavor.name) for flavor in flavors] else: for flavor in flavors: # If a flavor doesn't meet a minimum requirement, # do not add it to the options list and skip to the # next flavor. if flavor.vcpus < self.requirements.get('min_vcpus', 0): continue if flavor.disk < self.requirements.get('min_disk', 0): continue if flavor.ram < self.requirements.get('min_memory_mb', 0): continue if 'max_vcpus' in self.requirements: if flavor.vcpus > self.requirements['max_vcpus']: continue if 'max_disk' in self.requirements: if flavor.disk > self.requirements['max_disk']: continue if 'max_memory_mb' in self.requirements: if flavor.ram > self.requirements['max_memory_mb']: continue choices.append((flavor.id, flavor.name)) choices.sort(key=lambda e: e[1]) self.choices = choices if kwargs.get('form'): kwargs_form_flavor = kwargs["form"].fields.get('flavor') else: kwargs_form_flavor = None if kwargs_form_flavor: self.initial = kwargs["form"]["flavor"].value() else: # Search through selected flavors for flavor_id, flavor_name in self.choices: if 'medium' in flavor_name: self.initial = flavor_id break
def update(self, request, form=None, **kwargs): try: with helpers.current_region(request, getattr(form, 'region', None)): availability_zones = nova.novaclient( request).availability_zones.list(detailed=False) except Exception: availability_zones = [] exceptions.handle(request, _("Unable to retrieve availability zones.")) az_choices = [(az.zoneName, az.zoneName) for az in availability_zones if az.zoneState] if not az_choices: az_choices.insert(0, ("", _("No availability zones available"))) az_choices.sort(key=lambda e: e[1]) self.choices = az_choices
def usage_list(request, start, end): client = upgrade_api(request, _nova.novaclient(request), '2.40') usage_list = client.usage.list(start, end, True) if client.api_version >= api_versions.APIVersion('2.40'): # If the number of instances used to calculate the usage is greater # than max_limit, the usage will be split across multiple requests # and the responses will need to be merged back together. usages = collections.OrderedDict() _merge_usage_list(usages, usage_list) marker = _get_usage_list_marker(usage_list) while marker: next_usage_list = client.usage.list(start, end, True, marker=marker) marker = _get_usage_list_marker(next_usage_list) if marker: _merge_usage_list(usages, next_usage_list) usage_list = usages.values() return [NovaUsage(u) for u in usage_list]
def tenant_absolute_limits(request, reserved=False, tenant_id=None): # Nova does not allow to specify tenant_id for non-admin users # even if tenant_id matches a tenant_id of the user. if tenant_id == request.user.tenant_id: tenant_id = None limits = _nova.novaclient(request).limits.get(reserved=reserved, tenant_id=tenant_id).absolute limits_dict = {} for limit in limits: if limit.value < 0: # Workaround for nova bug 1370867 that absolute_limits # returns negative value for total.*Used instead of 0. # For such case, replace negative values with 0. if limit.name.startswith('total') and limit.name.endswith('Used'): limits_dict[limit.name] = 0 else: # -1 is used to represent unlimited quotas limits_dict[limit.name] = float("inf") else: limits_dict[limit.name] = limit.value return limits_dict
def flavor_access_list(request, flavor=None): """Get the list of access instance sizes (flavors).""" return _nova.novaclient(request).flavor_access.list(flavor=flavor)
def aggregate_get(request, aggregate_id): return _nova.novaclient(request).aggregates.get(aggregate_id)
def aggregate_create(request, name, availability_zone=None): return _nova.novaclient(request).aggregates.create(name, availability_zone)
def interface_attach(request, server, port_id=None, net_id=None, fixed_ip=None): return _nova.novaclient(request).servers.interface_attach( server, port_id, net_id, fixed_ip)
def aggregate_set_metadata(request, aggregate_id, metadata): return _nova.novaclient(request).aggregates.set_metadata(aggregate_id, metadata)
def server_spice_console(request, instance_id, console_type='spice-html5'): nc = _nova.novaclient(request) console = nc.servers.get_spice_console(instance_id, console_type) return SPICEConsole(console['console'])
def instance_action_list(request, instance_id): return nova_instance_action.InstanceActionManager( _nova.novaclient(request)).list(instance_id)
def service_disable(request, host, binary, reason=None): if reason: return _nova.novaclient(request).services.disable_log_reason( host, binary, reason) else: return _nova.novaclient(request).services.disable(host, binary)
def aggregate_create(request, name, availability_zone=None): return _nova.novaclient(request).aggregates.create(name, availability_zone)
def flavor_extra_set(request, flavor_id, metadata): """Set the flavor extra spec keys.""" flavor = _nova.novaclient(request).flavors.get(flavor_id) if (not metadata): # not a way to delete keys return None return flavor.set_keys(metadata)
def service_list(request, binary=None): return _nova.novaclient(request).services.list(binary=binary)
def flavor_extra_delete(request, flavor_id, keys): """Unset the flavor extra spec keys.""" flavor = _nova.novaclient(request).flavors.get(flavor_id) return flavor.unset_keys(keys)
def remove_tenant_from_flavor(request, flavor, tenant): """Remove a tenant from the given flavor access list.""" return _nova.novaclient(request).flavor_access.remove_tenant_access( flavor=flavor, tenant=tenant)
def add_tenant_to_flavor(request, flavor, tenant): """Add a tenant to the given flavor access list.""" return _nova.novaclient(request).flavor_access.add_tenant_access( flavor=flavor, tenant=tenant)
def server_serial_console(request, instance_id, console_type='serial'): nc = _nova.novaclient(request) console = nc.servers.get_serial_console(instance_id, console_type) return SerialConsole(console['console'])
def aggregate_get(request, aggregate_id): return _nova.novaclient(request).aggregates.get(aggregate_id)
def server_rdp_console(request, instance_id, console_type='rdp-html5'): nc = _nova.novaclient(request) console = nc.servers.get_rdp_console(instance_id, console_type) return RDPConsole(console['console'])
def aggregate_set_metadata(request, aggregate_id, metadata): return _nova.novaclient(request).aggregates.set_metadata(aggregate_id, metadata)
def server_vnc_console(request, instance_id, console_type='novnc'): nc = _nova.novaclient(request) console = nc.servers.get_vnc_console(instance_id, console_type) return VNCConsole(console['console'])
def remove_host_from_aggregate(request, aggregate_id, host): _nova.novaclient(request).aggregates.remove_host(aggregate_id, host)
def interface_detach(request, server, port_id): return _nova.novaclient(request).servers.interface_detach(server, port_id)
def flavor_delete(request, flavor_id): _nova.novaclient(request).flavors.delete(flavor_id)
def remove_host_from_aggregate(request, aggregate_id, host): _nova.novaclient(request).aggregates.remove_host(aggregate_id, host)
def server_unpause(request, instance_id): _nova.novaclient(request).servers.unpause(instance_id)
def aggregate_update(request, aggregate_id, values): _nova.novaclient(request).aggregates.update(aggregate_id, values)
def server_suspend(request, instance_id): _nova.novaclient(request).servers.suspend(instance_id)
def aggregate_delete(request, aggregate_id): return _nova.novaclient(request).aggregates.delete(aggregate_id)
def server_mks_console(request, instance_id, console_type='mks'): microver = get_microversion(request, "remote_console_mks") nc = _nova.novaclient(request, microver) console = nc.servers.get_mks_console(instance_id, console_type) return MKSConsole(console['remote_console'])
def snapshot_create(request, instance_id, name): return _nova.novaclient(request).servers.create_image(instance_id, name)
def flavor_get(request, flavor_id, get_extras=False): flavor = _nova.novaclient(request).flavors.get(flavor_id) if get_extras: flavor.extras = flavor_get_extras(request, flavor.id, True, flavor) return flavor
def service_enable(request, host, binary): return _nova.novaclient(request).services.enable(host, binary)
def keypair_import(request, name, public_key, key_type='ssh'): microversion = get_microversion(request, 'key_types') return _nova.novaclient(request, microversion).\ keypairs.create(name, public_key, key_type)
def aggregate_details_list(request): result = [] c = _nova.novaclient(request) for aggregate in c.aggregates.list(): result.append(c.aggregates.get_details(aggregate.id)) return result
def keypair_delete(request, name): _nova.novaclient(request).keypairs.delete(name)
def aggregate_delete(request, aggregate_id): return _nova.novaclient(request).aggregates.delete(aggregate_id)
def keypair_list(request): microversion = get_microversion(request, 'key_type_list') return _nova.novaclient(request, microversion).keypairs.list()
def aggregate_update(request, aggregate_id, values): _nova.novaclient(request).aggregates.update(aggregate_id, values)
def keypair_get(request, name): return _nova.novaclient(request).keypairs.get(name)
def add_host_to_aggregate(request, aggregate_id, host): _nova.novaclient(request).aggregates.add_host(aggregate_id, host)
def get_novaclient_with_locked_status(request): microversion = get_microversion(request, "locked_attribute") return _nova.novaclient(request, version=microversion)
def interface_attach(request, server, port_id=None, net_id=None, fixed_ip=None): return _nova.novaclient(request).servers.interface_attach( server, port_id, net_id, fixed_ip)
def server_console_output(request, instance_id, tail_length=None): """Gets console output of an instance.""" nc = _nova.novaclient(request) return nc.servers.get_console_output(instance_id, length=tail_length)