Buckets:
| '\nA driver wrapping the Ironic API, such that Nova may provision\nbare metal resources.\n' | |
| import base64 | |
| import gzip | |
| import shutil | |
| import tempfile | |
| import time | |
| from oslo_log import log as logging | |
| from oslo_serialization import jsonutils | |
| from oslo_service import loopingcall | |
| from oslo_utils import excutils | |
| from oslo_utils import importutils | |
| import six | |
| import six.moves.urllib.parse as urlparse | |
| from tooz import hashring as hash_ring | |
| from nova.api.metadata import base as instance_metadata | |
| from nova import block_device | |
| from nova.compute import power_state | |
| from nova.compute import task_states | |
| from nova.compute import vm_states | |
| import nova.conf | |
| from nova.console import type as console_type | |
| from nova import context as nova_context | |
| from nova import exception | |
| from nova.i18n import _ | |
| from nova import objects | |
| from nova.objects import fields as obj_fields | |
| from nova import servicegroup | |
| from nova import utils | |
| from nova.virt import configdrive | |
| from nova.virt import driver as virt_driver | |
| from nova.virt import firewall | |
| from nova.virt import hardware | |
| from nova.virt.ironic import client_wrapper | |
| from nova.virt.ironic import ironic_states | |
| from nova.virt.ironic import patcher | |
| from nova.virt import netutils | |
| ironic = None | |
| LOG = logging.getLogger(__name__) | |
| CONF = nova.conf.CONF | |
| _POWER_STATE_MAP = {ironic_states.POWER_ON: power_state.RUNNING, ironic_states.NOSTATE: power_state.NOSTATE, ironic_states.POWER_OFF: power_state.SHUTDOWN} | |
| _UNPROVISION_STATES = (ironic_states.ACTIVE, ironic_states.DEPLOYFAIL, ironic_states.ERROR, ironic_states.DEPLOYWAIT, ironic_states.DEPLOYING) | |
| _NODE_FIELDS = ('uuid', 'power_state', 'target_power_state', 'provision_state', 'target_provision_state', 'last_error', 'maintenance', 'properties', 'instance_uuid') | |
| _CONSOLE_STATE_CHECKING_INTERVAL = 1 | |
| _HASH_RING_PARTITIONS = (2 ** 5) | |
| def map_power_state(state): | |
| try: | |
| return _POWER_STATE_MAP[state] | |
| except KeyError: | |
| LOG.warning('Power state %s not found.', state) | |
| return power_state.NOSTATE | |
| def _get_nodes_supported_instances(cpu_arch=None): | |
| 'Return supported instances for a node.' | |
| if (not cpu_arch): | |
| return [] | |
| return [(cpu_arch, obj_fields.HVType.BAREMETAL, obj_fields.VMMode.HVM)] | |
| def _log_ironic_polling(what, node, instance): | |
| power_state = (None if (node.power_state is None) else ('"%s"' % node.power_state)) | |
| tgt_power_state = (None if (node.target_power_state is None) else ('"%s"' % node.target_power_state)) | |
| prov_state = (None if (node.provision_state is None) else ('"%s"' % node.provision_state)) | |
| tgt_prov_state = (None if (node.target_provision_state is None) else ('"%s"' % node.target_provision_state)) | |
| LOG.debug('Still waiting for ironic node %(node)s to %(what)s: power_state=%(power_state)s, target_power_state=%(tgt_power_state)s, provision_state=%(prov_state)s, target_provision_state=%(tgt_prov_state)s', dict(what=what, node=node.uuid, power_state=power_state, tgt_power_state=tgt_power_state, prov_state=prov_state, tgt_prov_state=tgt_prov_state), instance=instance) | |
| class IronicDriver(virt_driver.ComputeDriver, ): | |
| 'Hypervisor driver for Ironic - bare metal provisioning.' | |
| capabilities = {'has_imagecache': False, 'supports_recreate': False, 'supports_migrate_to_same_host': False, 'supports_attach_interface': True} | |
| requires_allocation_refresh = True | |
| rebalances_nodes = True | |
| def __init__(self, virtapi, read_only=False): | |
| super(IronicDriver, self).__init__(virtapi) | |
| global ironic | |
| if (ironic is None): | |
| ironic = importutils.import_module('ironicclient') | |
| if (not hasattr(ironic, 'exc')): | |
| ironic.exc = importutils.import_module('ironicclient.exc') | |
| if (not hasattr(ironic, 'client')): | |
| ironic.client = importutils.import_module('ironicclient.client') | |
| self.firewall_driver = firewall.load_driver(default='nova.virt.firewall.NoopFirewallDriver') | |
| self.node_cache = {} | |
| self.node_cache_time = 0 | |
| self.servicegroup_api = servicegroup.API() | |
| self.ironicclient = client_wrapper.IronicClientWrapper() | |
| self._migrated_instance_uuids = set() | |
| def _get_node(self, node_uuid): | |
| 'Get a node by its UUID.' | |
| return self.ironicclient.call('node.get', node_uuid, fields=_NODE_FIELDS) | |
| def _validate_instance_and_node(self, instance): | |
| 'Get the node associated with the instance.\n\n Check with the Ironic service that this instance is associated with a\n node, and return the node.\n ' | |
| try: | |
| return self.ironicclient.call('node.get_by_instance_uuid', instance.uuid, fields=_NODE_FIELDS) | |
| except ironic.exc.NotFound: | |
| raise exception.InstanceNotFound(instance_id=instance.uuid) | |
| def _node_resources_unavailable(self, node_obj): | |
| "Determine whether the node's resources are in an acceptable state.\n\n Determines whether the node's resources should be presented\n to Nova for use based on the current power, provision and maintenance\n state. This is called after _node_resources_used, so any node that\n is not used and not in AVAILABLE should be considered in a 'bad' state,\n and unavailable for scheduling. Returns True if unacceptable.\n " | |
| bad_power_states = [ironic_states.ERROR, ironic_states.NOSTATE] | |
| good_provision_states = [ironic_states.AVAILABLE, ironic_states.NOSTATE] | |
| return (node_obj.maintenance or (node_obj.power_state in bad_power_states) or (node_obj.provision_state not in good_provision_states)) | |
| def _node_resources_used(self, node_obj): | |
| "Determine whether the node's resources are currently used.\n\n Determines whether the node's resources should be considered used\n or not. A node is used when it is either in the process of putting\n a new instance on the node, has an instance on the node, or is in\n the process of cleaning up from a deleted instance. Returns True if\n used.\n\n If we report resources as consumed for a node that does not have an\n instance on it, the resource tracker will notice there's no instances\n consuming resources and try to correct us. So only nodes with an\n instance attached should report as consumed here.\n " | |
| return (node_obj.instance_uuid is not None) | |
| def _parse_node_properties(self, node): | |
| "Helper method to parse the node's properties." | |
| properties = {} | |
| for prop in ('cpus', 'memory_mb', 'local_gb'): | |
| try: | |
| properties[prop] = int(node.properties.get(prop, 0)) | |
| except (TypeError, ValueError): | |
| LOG.warning('Node %(uuid)s has a malformed "%(prop)s". It should be an integer.', {'uuid': node.uuid, 'prop': prop}) | |
| properties[prop] = 0 | |
| raw_cpu_arch = node.properties.get('cpu_arch', None) | |
| try: | |
| cpu_arch = obj_fields.Architecture.canonicalize(raw_cpu_arch) | |
| except exception.InvalidArchitectureName: | |
| cpu_arch = None | |
| if (not cpu_arch): | |
| LOG.warning("cpu_arch not defined for node '%s'", node.uuid) | |
| properties['cpu_arch'] = cpu_arch | |
| properties['raw_cpu_arch'] = raw_cpu_arch | |
| properties['capabilities'] = node.properties.get('capabilities') | |
| return properties | |
| def _parse_node_instance_info(self, node, props): | |
| "Helper method to parse the node's instance info.\n\n If a property cannot be looked up via instance_info, use the original\n value from the properties dict. This is most likely to be correct;\n it should only be incorrect if the properties were changed directly\n in Ironic while an instance was deployed.\n " | |
| instance_info = {} | |
| props['vcpus'] = props['cpus'] | |
| for prop in ('vcpus', 'memory_mb', 'local_gb'): | |
| original = props[prop] | |
| try: | |
| instance_info[prop] = int(node.instance_info.get(prop, original)) | |
| except (TypeError, ValueError): | |
| LOG.warning('Node %(uuid)s has a malformed "%(prop)s". It should be an integer but its value is "%(value)s".', {'uuid': node.uuid, 'prop': prop, 'value': node.instance_info.get(prop)}) | |
| instance_info[prop] = original | |
| return instance_info | |
| def _node_resource(self, node): | |
| 'Helper method to create resource dict from node stats.' | |
| properties = self._parse_node_properties(node) | |
| vcpus = properties['cpus'] | |
| memory_mb = properties['memory_mb'] | |
| local_gb = properties['local_gb'] | |
| raw_cpu_arch = properties['raw_cpu_arch'] | |
| cpu_arch = properties['cpu_arch'] | |
| nodes_extra_specs = {} | |
| nodes_extra_specs['cpu_arch'] = raw_cpu_arch | |
| capabilities = properties['capabilities'] | |
| if capabilities: | |
| for capability in str(capabilities).split(','): | |
| parts = capability.split(':') | |
| if ((len(parts) == 2) and parts[0] and parts[1]): | |
| nodes_extra_specs[parts[0].strip()] = parts[1] | |
| else: | |
| LOG.warning("Ignoring malformed capability '%s'. Format should be 'key:val'.", capability) | |
| vcpus_used = 0 | |
| memory_mb_used = 0 | |
| local_gb_used = 0 | |
| if self._node_resources_used(node): | |
| vcpus_used = vcpus | |
| memory_mb_used = memory_mb | |
| local_gb_used = local_gb | |
| elif self._node_resources_unavailable(node): | |
| vcpus = 0 | |
| memory_mb = 0 | |
| local_gb = 0 | |
| dic = {'hypervisor_hostname': str(node.uuid), 'hypervisor_type': self._get_hypervisor_type(), 'hypervisor_version': self._get_hypervisor_version(), 'resource_class': node.resource_class, 'cpu_info': None, 'vcpus': vcpus, 'vcpus_used': vcpus_used, 'local_gb': local_gb, 'local_gb_used': local_gb_used, 'disk_available_least': (local_gb - local_gb_used), 'memory_mb': memory_mb, 'memory_mb_used': memory_mb_used, 'supported_instances': _get_nodes_supported_instances(cpu_arch), 'stats': nodes_extra_specs, 'numa_topology': None} | |
| return dic | |
| def _start_firewall(self, instance, network_info): | |
| self.firewall_driver.setup_basic_filtering(instance, network_info) | |
| self.firewall_driver.prepare_instance_filter(instance, network_info) | |
| self.firewall_driver.apply_instance_filter(instance, network_info) | |
| def _stop_firewall(self, instance, network_info): | |
| self.firewall_driver.unfilter_instance(instance, network_info) | |
| def _add_instance_info_to_node(self, node, instance, image_meta, flavor, preserve_ephemeral=None, block_device_info=None): | |
| root_bdm = block_device.get_root_bdm(virt_driver.block_device_info_get_mapping(block_device_info)) | |
| boot_from_volume = (root_bdm is not None) | |
| patch = patcher.create(node).get_deploy_patch(instance, image_meta, flavor, preserve_ephemeral, boot_from_volume) | |
| patch.append({'path': '/instance_uuid', 'op': 'add', 'value': instance.uuid}) | |
| try: | |
| self.ironicclient.call('node.update', node.uuid, patch, retry_on_conflict=False) | |
| except ironic.exc.BadRequest: | |
| msg = (_('Failed to add deploy parameters on node %(node)s when provisioning the instance %(instance)s') % {'node': node.uuid, 'instance': instance.uuid}) | |
| LOG.error(msg) | |
| raise exception.InstanceDeployFailure(msg) | |
| def _remove_instance_info_from_node(self, node, instance): | |
| patch = [{'path': '/instance_info', 'op': 'remove'}, {'path': '/instance_uuid', 'op': 'remove'}] | |
| try: | |
| self.ironicclient.call('node.update', node.uuid, patch) | |
| except ironic.exc.BadRequest as e: | |
| LOG.warning('Failed to remove deploy parameters from node %(node)s when unprovisioning the instance %(instance)s: %(reason)s', {'node': node.uuid, 'instance': instance.uuid, 'reason': six.text_type(e)}) | |
| def _add_volume_target_info(self, context, instance, block_device_info): | |
| bdms = virt_driver.block_device_info_get_mapping(block_device_info) | |
| for bdm in bdms: | |
| if (not bdm._bdm_obj.is_volume): | |
| continue | |
| connection_info = jsonutils.loads(bdm._bdm_obj.connection_info) | |
| target_properties = connection_info['data'] | |
| driver_volume_type = connection_info['driver_volume_type'] | |
| try: | |
| self.ironicclient.call('volume_target.create', node_uuid=instance.node, volume_type=driver_volume_type, properties=target_properties, boot_index=bdm._bdm_obj.boot_index, volume_id=bdm._bdm_obj.volume_id) | |
| except (ironic.exc.BadRequest, ironic.exc.Conflict): | |
| msg = (_('Failed to add volume target information of volume %(volume)s on node %(node)s when provisioning the instance') % {'volume': bdm._bdm_obj.volume_id, 'node': instance.node}) | |
| LOG.error(msg, instance=instance) | |
| raise exception.InstanceDeployFailure(msg) | |
| def _cleanup_volume_target_info(self, instance): | |
| targets = self.ironicclient.call('node.list_volume_targets', instance.node, detail=True) | |
| for target in targets: | |
| volume_target_id = target.uuid | |
| try: | |
| self.ironicclient.call('volume_target.delete', volume_target_id) | |
| except ironic.exc.NotFound: | |
| LOG.debug('Volume target information %(target)s of volume %(volume)s is already removed from node %(node)s', {'target': volume_target_id, 'volume': target.volume_id, 'node': instance.node}, instance=instance) | |
| except ironic.exc.ClientException as e: | |
| LOG.warning('Failed to remove volume target information %(target)s of volume %(volume)s from node %(node)s when unprovisioning the instance: %(reason)s', {'target': volume_target_id, 'volume': target.volume_id, 'node': instance.node, 'reason': e}, instance=instance) | |
| def _cleanup_deploy(self, node, instance, network_info): | |
| self._cleanup_volume_target_info(instance) | |
| self._unplug_vifs(node, instance, network_info) | |
| self._stop_firewall(instance, network_info) | |
| def _wait_for_active(self, instance): | |
| 'Wait for the node to be marked as ACTIVE in Ironic.' | |
| instance.refresh() | |
| if ((instance.task_state == task_states.DELETING) or (instance.vm_state in (vm_states.ERROR, vm_states.DELETED))): | |
| raise exception.InstanceDeployFailure((_('Instance %s provisioning was aborted') % instance.uuid)) | |
| node = self._validate_instance_and_node(instance) | |
| if (node.provision_state == ironic_states.ACTIVE): | |
| LOG.debug('Ironic node %(node)s is now ACTIVE', dict(node=node.uuid), instance=instance) | |
| raise loopingcall.LoopingCallDone() | |
| if (node.target_provision_state in (ironic_states.DELETED, ironic_states.AVAILABLE)): | |
| raise exception.InstanceNotFound(instance_id=instance.uuid) | |
| if (node.provision_state in (ironic_states.NOSTATE, ironic_states.AVAILABLE)): | |
| raise exception.InstanceNotFound(instance_id=instance.uuid) | |
| if (node.provision_state == ironic_states.DEPLOYFAIL): | |
| msg = (_('Failed to provision instance %(inst)s: %(reason)s') % {'inst': instance.uuid, 'reason': node.last_error}) | |
| raise exception.InstanceDeployFailure(msg) | |
| _log_ironic_polling('become ACTIVE', node, instance) | |
| def _wait_for_power_state(self, instance, message): | |
| 'Wait for the node to complete a power state change.' | |
| node = self._validate_instance_and_node(instance) | |
| if (node.target_power_state == ironic_states.NOSTATE): | |
| raise loopingcall.LoopingCallDone() | |
| _log_ironic_polling(message, node, instance) | |
| def init_host(self, host): | |
| 'Initialize anything that is necessary for the driver to function.\n\n :param host: the hostname of the compute host.\n\n ' | |
| self._refresh_hash_ring(nova_context.get_admin_context()) | |
| @staticmethod | |
| def _pike_flavor_migration_for_node(ctx, node_rc, instance_uuid): | |
| normalized_rc = obj_fields.ResourceClass.normalize_name(node_rc) | |
| instance = objects.Instance.get_by_uuid(ctx, instance_uuid, expected_attrs=['flavor']) | |
| specs = instance.flavor.extra_specs | |
| resource_key = ('resources:%s' % normalized_rc) | |
| if (resource_key in specs): | |
| return False | |
| specs[resource_key] = '1' | |
| instance.save() | |
| return True | |
| def _pike_flavor_migration(self, node_uuids): | |
| 'This code is needed in Pike to prevent problems where an operator\n has already adjusted their flavors to add the custom resource class to\n extra_specs. Since existing ironic instances will not have this in\n their extra_specs, they will only have allocations against\n VCPU/RAM/disk. By adding just the custom RC to the existing flavor\n extra_specs, the periodic call to update_available_resources() will add\n an allocation against the custom resource class, and prevent placement\n from thinking that that node is available. This code can be removed in\n Queens, and will need to be updated to also alter extra_specs to\n zero-out the old-style standard resource classes of VCPU, MEMORY_MB,\n and DISK_GB.\n ' | |
| ctx = nova_context.get_admin_context() | |
| for node_uuid in node_uuids: | |
| node = self._node_from_cache(node_uuid) | |
| if (not node): | |
| continue | |
| node_rc = node.resource_class | |
| if (not node_rc): | |
| LOG.warning('Node %(node)s does not have its resource_class set.', {'node': node.uuid}) | |
| continue | |
| if (node.instance_uuid in self._migrated_instance_uuids): | |
| continue | |
| self._pike_flavor_migration_for_node(ctx, node_rc, node.instance_uuid) | |
| self._migrated_instance_uuids.add(node.instance_uuid) | |
| LOG.debug("The flavor extra_specs for Ironic instance %(inst)s have been updated for custom resource class '%(rc)s'.", {'inst': node.instance_uuid, 'rc': node_rc}) | |
| return | |
| def _get_hypervisor_type(self): | |
| 'Get hypervisor type.' | |
| return 'ironic' | |
| def _get_hypervisor_version(self): | |
| 'Returns the version of the Ironic API service endpoint.' | |
| return client_wrapper.IRONIC_API_VERSION[0] | |
| def instance_exists(self, instance): | |
| 'Checks the existence of an instance.\n\n Checks the existence of an instance. This is an override of the\n base method for efficiency.\n\n :param instance: The instance object.\n :returns: True if the instance exists. False if not.\n\n ' | |
| try: | |
| self._validate_instance_and_node(instance) | |
| return True | |
| except exception.InstanceNotFound: | |
| return False | |
| def _get_node_list(self, **kwargs): | |
| 'Helper function to return the list of nodes.\n\n If unable to connect ironic server, an empty list is returned.\n\n :returns: a list of raw node from ironic\n\n ' | |
| node_list = [] | |
| try: | |
| node_list = self.ironicclient.call('node.list', **kwargs) | |
| except exception.NovaException as e: | |
| LOG.error('Failed to get the list of nodes from the Ironic inventory. Error: %s', e) | |
| except Exception as e: | |
| LOG.error('An unknown error has occurred when trying to get the list of nodes from the Ironic inventory. Error: %s', e) | |
| return node_list | |
| def list_instances(self): | |
| 'Return the names of all the instances provisioned.\n\n :returns: a list of instance names.\n\n ' | |
| node_list = self._get_node_list(associated=True, limit=0) | |
| context = nova_context.get_admin_context() | |
| return [objects.Instance.get_by_uuid(context, i.instance_uuid).name for i in node_list] | |
| def list_instance_uuids(self): | |
| 'Return the UUIDs of all the instances provisioned.\n\n :returns: a list of instance UUIDs.\n\n ' | |
| return list((n.instance_uuid for n in self._get_node_list(associated=True, limit=0))) | |
| def node_is_available(self, nodename): | |
| 'Confirms a Nova hypervisor node exists in the Ironic inventory.\n\n :param nodename: The UUID of the node.\n :returns: True if the node exists, False if not.\n\n ' | |
| if (not self.node_cache): | |
| self._refresh_cache() | |
| if (nodename in self.node_cache): | |
| return True | |
| try: | |
| self._get_node(nodename) | |
| return True | |
| except ironic.exc.NotFound: | |
| return False | |
| def _refresh_hash_ring(self, ctxt): | |
| service_list = objects.ServiceList.get_all_computes_by_hv_type(ctxt, self._get_hypervisor_type()) | |
| services = set() | |
| for svc in service_list: | |
| is_up = self.servicegroup_api.service_is_up(svc) | |
| if is_up: | |
| services.add(svc.host) | |
| services.add(CONF.host) | |
| self.hash_ring = hash_ring.HashRing(services, partitions=_HASH_RING_PARTITIONS) | |
| def _refresh_cache(self): | |
| ctxt = nova_context.get_admin_context() | |
| self._refresh_hash_ring(ctxt) | |
| instances = objects.InstanceList.get_uuids_by_host(ctxt, CONF.host) | |
| node_cache = {} | |
| for node in self._get_node_list(detail=True, limit=0): | |
| if (node.instance_uuid in instances): | |
| node_cache[node.uuid] = node | |
| elif ((node.instance_uuid is None) and (CONF.host in self.hash_ring.get_nodes(node.uuid.encode('utf-8')))): | |
| node_cache[node.uuid] = node | |
| self.node_cache = node_cache | |
| self.node_cache_time = time.time() | |
| node_uuids = [node.uuid for node in self.node_cache.values() if (node.instance_uuid and (node.instance_uuid not in self._migrated_instance_uuids))] | |
| if node_uuids: | |
| utils.spawn_n(self._pike_flavor_migration, node_uuids) | |
| def get_available_nodes(self, refresh=False): | |
| 'Returns the UUIDs of Ironic nodes managed by this compute service.\n\n We use consistent hashing to distribute Ironic nodes between all\n available compute services. The subset of nodes managed by a given\n compute service is determined by the following rules:\n\n * any node with an instance managed by the compute service\n * any node that is mapped to the compute service on the hash ring\n * no nodes with instances managed by another compute service\n\n The ring is rebalanced as nova-compute services are brought up and\n down. Note that this rebalance does not happen at the same time for\n all compute services, so a node may be managed by multiple compute\n services for a small amount of time.\n\n :param refresh: Boolean value; If True run update first. Ignored by\n this driver.\n :returns: a list of UUIDs\n\n ' | |
| self._refresh_cache() | |
| node_uuids = list(self.node_cache.keys()) | |
| LOG.debug('Returning %(num_nodes)s available node(s)', dict(num_nodes=len(node_uuids))) | |
| return node_uuids | |
| def get_inventory(self, nodename): | |
| 'Return a dict, keyed by resource class, of inventory information for\n the supplied node.\n ' | |
| node = self._node_from_cache(nodename) | |
| if ((not self._node_resources_used(node)) and self._node_resources_unavailable(node)): | |
| LOG.debug("Node %(node)s is not ready for a deployment, reporting an empty inventory for it. Node's provision state is %(prov)s, power state is %(power)s and maintenance is %(maint)s.", {'node': node.uuid, 'prov': node.provision_state, 'power': node.power_state, 'maint': node.maintenance}) | |
| return {} | |
| info = self._node_resource(node) | |
| result = {} | |
| for (rc, field) in [(obj_fields.ResourceClass.VCPU, 'vcpus'), (obj_fields.ResourceClass.MEMORY_MB, 'memory_mb'), (obj_fields.ResourceClass.DISK_GB, 'local_gb')]: | |
| if info[field]: | |
| result[rc] = {'total': info[field], 'reserved': 0, 'min_unit': 1, 'max_unit': info[field], 'step_size': 1, 'allocation_ratio': 1.0} | |
| rc_name = info.get('resource_class') | |
| if (rc_name is not None): | |
| norm_name = obj_fields.ResourceClass.normalize_name(rc_name) | |
| if (norm_name is not None): | |
| result[norm_name] = {'total': 1, 'reserved': 0, 'min_unit': 1, 'max_unit': 1, 'step_size': 1, 'allocation_ratio': 1.0} | |
| return result | |
| def get_available_resource(self, nodename): | |
| 'Retrieve resource information.\n\n This method is called when nova-compute launches, and\n as part of a periodic task that records the results in the DB.\n\n :param nodename: the UUID of the node.\n :returns: a dictionary describing resources.\n\n ' | |
| if (not self.node_cache): | |
| self._refresh_cache() | |
| node = self._node_from_cache(nodename) | |
| return self._node_resource(node) | |
| def _node_from_cache(self, nodename): | |
| "Returns a node from the cache, retrieving the node from Ironic API\n if the node doesn't yet exist in the cache.\n " | |
| cache_age = (time.time() - self.node_cache_time) | |
| if (nodename in self.node_cache): | |
| LOG.debug('Using cache for node %(node)s, age: %(age)s', {'node': nodename, 'age': cache_age}) | |
| return self.node_cache[nodename] | |
| else: | |
| LOG.debug('Node %(node)s not found in cache, age: %(age)s', {'node': nodename, 'age': cache_age}) | |
| node = self._get_node(nodename) | |
| self.node_cache[nodename] = node | |
| return node | |
| def get_info(self, instance): | |
| 'Get the current state and resource usage for this instance.\n\n If the instance is not found this method returns (a dictionary\n with) NOSTATE and all resources == 0.\n\n :param instance: the instance object.\n :returns: a InstanceInfo object\n ' | |
| try: | |
| node = self._validate_instance_and_node(instance) | |
| except exception.InstanceNotFound: | |
| return hardware.InstanceInfo(state=map_power_state(ironic_states.NOSTATE)) | |
| properties = self._parse_node_properties(node) | |
| memory_kib = (properties['memory_mb'] * 1024) | |
| if (memory_kib == 0): | |
| LOG.warning('Warning, memory usage is 0 for %(instance)s on baremetal node %(node)s.', {'instance': instance.uuid, 'node': instance.node}) | |
| num_cpu = properties['cpus'] | |
| if (num_cpu == 0): | |
| LOG.warning('Warning, number of cpus is 0 for %(instance)s on baremetal node %(node)s.', {'instance': instance.uuid, 'node': instance.node}) | |
| return hardware.InstanceInfo(state=map_power_state(node.power_state), max_mem_kb=memory_kib, mem_kb=memory_kib, num_cpu=num_cpu) | |
| def deallocate_networks_on_reschedule(self, instance): | |
| 'Does the driver want networks deallocated on reschedule?\n\n :param instance: the instance object.\n :returns: Boolean value. If True deallocate networks on reschedule.\n ' | |
| return True | |
| def _get_network_metadata(self, node, network_info): | |
| 'Gets a more complete representation of the instance network info.\n\n This data is exposed as network_data.json in the metadata service and\n the config drive.\n\n :param node: The node object.\n :param network_info: Instance network information.\n ' | |
| base_metadata = netutils.get_network_metadata(network_info) | |
| ports = self.ironicclient.call('node.list_ports', node.uuid, detail=True) | |
| portgroups = self.ironicclient.call('portgroup.list', node=node.uuid, detail=True) | |
| vif_id_to_objects = {'ports': {}, 'portgroups': {}} | |
| for (collection, name) in ((ports, 'ports'), (portgroups, 'portgroups')): | |
| for p in collection: | |
| vif_id = (p.internal_info.get('tenant_vif_port_id') or p.extra.get('vif_port_id')) | |
| if vif_id: | |
| vif_id_to_objects[name][vif_id] = p | |
| additional_links = [] | |
| for link in base_metadata['links']: | |
| vif_id = link['vif_id'] | |
| if (vif_id in vif_id_to_objects['portgroups']): | |
| pg = vif_id_to_objects['portgroups'][vif_id] | |
| pg_ports = [p for p in ports if (p.portgroup_uuid == pg.uuid)] | |
| link.update({'type': 'bond', 'bond_mode': pg.mode, 'bond_links': []}) | |
| if pg.address: | |
| link.update({'ethernet_mac_address': pg.address}) | |
| for prop in pg.properties: | |
| key = (prop if prop.startswith('bond') else ('bond_%s' % prop)) | |
| link[key] = pg.properties[prop] | |
| for port in pg_ports: | |
| additional_links.append({'id': port.uuid, 'type': 'phy', 'ethernet_mac_address': port.address}) | |
| link['bond_links'].append(port.uuid) | |
| elif (vif_id in vif_id_to_objects['ports']): | |
| p = vif_id_to_objects['ports'][vif_id] | |
| link.update({'ethernet_mac_address': p.address, 'type': 'phy'}) | |
| base_metadata['links'].extend(additional_links) | |
| return base_metadata | |
| def _generate_configdrive(self, context, instance, node, network_info, extra_md=None, files=None): | |
| 'Generate a config drive.\n\n :param instance: The instance object.\n :param node: The node object.\n :param network_info: Instance network information.\n :param extra_md: Optional, extra metadata to be added to the\n configdrive.\n :param files: Optional, a list of paths to files to be added to\n the configdrive.\n\n ' | |
| if (not extra_md): | |
| extra_md = {} | |
| i_meta = instance_metadata.InstanceMetadata(instance, content=files, extra_md=extra_md, network_info=network_info, network_metadata=self._get_network_metadata(node, network_info), request_context=context) | |
| with tempfile.NamedTemporaryFile() as uncompressed: | |
| with configdrive.ConfigDriveBuilder(instance_md=i_meta) as cdb: | |
| cdb.make_drive(uncompressed.name) | |
| with tempfile.NamedTemporaryFile() as compressed: | |
| with gzip.GzipFile(fileobj=compressed, mode='wb') as gzipped: | |
| uncompressed.seek() | |
| shutil.copyfileobj(uncompressed, gzipped) | |
| compressed.seek(0) | |
| return base64.b64encode(compressed.read()) | |
| def spawn(self, context, instance, image_meta, injected_files, admin_password, network_info=None, block_device_info=None): | |
| 'Deploy an instance.\n\n :param context: The security context.\n :param instance: The instance object.\n :param image_meta: Image dict returned by nova.image.glance\n that defines the image from which to boot this instance.\n :param injected_files: User files to inject into instance.\n :param admin_password: Administrator password to set in\n instance.\n :param network_info: Instance network information.\n :param block_device_info: Instance block device\n information.\n ' | |
| LOG.debug('Spawn called for instance', instance=instance) | |
| node_uuid = instance.get('node') | |
| if (not node_uuid): | |
| raise ironic.exc.BadRequest((_('Ironic node uuid not supplied to driver for instance %s.') % instance.uuid)) | |
| node = self._get_node(node_uuid) | |
| flavor = instance.flavor | |
| self._add_instance_info_to_node(node, instance, image_meta, flavor, block_device_info=block_device_info) | |
| try: | |
| self._add_volume_target_info(context, instance, block_device_info) | |
| except Exception: | |
| with excutils.save_and_reraise_exception(): | |
| LOG.error('Error preparing deploy for instance on baremetal node %(node)s.', {'node': node_uuid}, instance=instance) | |
| self._cleanup_deploy(node, instance, network_info) | |
| if flavor.ephemeral_gb: | |
| instance.default_ephemeral_device = '/dev/sda1' | |
| instance.save() | |
| validate_chk = self.ironicclient.call('node.validate', node_uuid) | |
| if ((not validate_chk.deploy.get('result')) or (not validate_chk.power.get('result')) or (not validate_chk.storage.get('result'))): | |
| self._cleanup_deploy(node, instance, network_info) | |
| raise exception.ValidationError((_('Ironic node: %(id)s failed to validate. (deploy: %(deploy)s, power: %(power)s, storage: %(storage)s)') % {'id': node.uuid, 'deploy': validate_chk.deploy, 'power': validate_chk.power, 'storage': validate_chk.storage})) | |
| try: | |
| self._plug_vifs(node, instance, network_info) | |
| self._start_firewall(instance, network_info) | |
| except Exception: | |
| with excutils.save_and_reraise_exception(): | |
| LOG.error('Error preparing deploy for instance %(instance)s on baremetal node %(node)s.', {'instance': instance.uuid, 'node': node_uuid}) | |
| self._cleanup_deploy(node, instance, network_info) | |
| configdrive_value = None | |
| if configdrive.required_by(instance): | |
| extra_md = {} | |
| if admin_password: | |
| extra_md['admin_pass'] = admin_password | |
| try: | |
| configdrive_value = self._generate_configdrive(context, instance, node, network_info, extra_md=extra_md, files=injected_files) | |
| except Exception as e: | |
| with excutils.save_and_reraise_exception(): | |
| msg = ('Failed to build configdrive: %s' % six.text_type(e)) | |
| LOG.error(msg, instance=instance) | |
| self._cleanup_deploy(node, instance, network_info) | |
| LOG.info('Config drive for instance %(instance)s on baremetal node %(node)s created.', {'instance': instance['uuid'], 'node': node_uuid}) | |
| try: | |
| self.ironicclient.call('node.set_provision_state', node_uuid, ironic_states.ACTIVE, configdrive=configdrive_value) | |
| except Exception as e: | |
| with excutils.save_and_reraise_exception(): | |
| LOG.error('Failed to request Ironic to provision instance %(inst)s: %(reason)s', {'inst': instance.uuid, 'reason': six.text_type(e)}) | |
| self._cleanup_deploy(node, instance, network_info) | |
| timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_active, instance) | |
| try: | |
| timer.start(interval=CONF.ironic.api_retry_interval).wait() | |
| LOG.info('Successfully provisioned Ironic node %s', node.uuid, instance=instance) | |
| except Exception: | |
| with excutils.save_and_reraise_exception(): | |
| LOG.error('Error deploying instance %(instance)s on baremetal node %(node)s.', {'instance': instance.uuid, 'node': node_uuid}) | |
| def _unprovision(self, instance, node): | |
| 'This method is called from destroy() to unprovision\n already provisioned node after required checks.\n ' | |
| try: | |
| self.ironicclient.call('node.set_provision_state', node.uuid, 'deleted') | |
| except Exception as e: | |
| if (getattr(e, '__name__', None) != 'InstanceDeployFailure'): | |
| raise | |
| data = {'tries': 0} | |
| def _wait_for_provision_state(): | |
| try: | |
| node = self._validate_instance_and_node(instance) | |
| except exception.InstanceNotFound: | |
| LOG.debug('Instance already removed from Ironic', instance=instance) | |
| raise loopingcall.LoopingCallDone() | |
| if (node.provision_state in (ironic_states.NOSTATE, ironic_states.CLEANING, ironic_states.CLEANWAIT, ironic_states.CLEANFAIL, ironic_states.AVAILABLE)): | |
| LOG.debug('Ironic node %(node)s is in state %(state)s, instance is now unprovisioned.', dict(node=node.uuid, state=node.provision_state), instance=instance) | |
| raise loopingcall.LoopingCallDone() | |
| if (data['tries'] >= (CONF.ironic.api_max_retries + 1)): | |
| msg = (_("Error destroying the instance on node %(node)s. Provision state still '%(state)s'.") % {'state': node.provision_state, 'node': node.uuid}) | |
| LOG.error(msg) | |
| raise exception.NovaException(msg) | |
| else: | |
| data['tries'] += 1 | |
| _log_ironic_polling('unprovision', node, instance) | |
| timer = loopingcall.FixedIntervalLoopingCall(_wait_for_provision_state) | |
| timer.start(interval=CONF.ironic.api_retry_interval).wait() | |
| def destroy(self, context, instance, network_info, block_device_info=None, destroy_disks=True): | |
| 'Destroy the specified instance, if it can be found.\n\n :param context: The security context.\n :param instance: The instance object.\n :param network_info: Instance network information.\n :param block_device_info: Instance block device\n information. Ignored by this driver.\n :param destroy_disks: Indicates if disks should be\n destroyed. Ignored by this driver.\n ' | |
| LOG.debug('Destroy called for instance', instance=instance) | |
| try: | |
| node = self._validate_instance_and_node(instance) | |
| except exception.InstanceNotFound: | |
| LOG.warning('Destroy called on non-existing instance %s.', instance.uuid) | |
| return | |
| if (node.provision_state in _UNPROVISION_STATES): | |
| self._unprovision(instance, node) | |
| else: | |
| self._remove_instance_info_from_node(node, instance) | |
| self._cleanup_deploy(node, instance, network_info) | |
| LOG.info('Successfully unprovisioned Ironic node %s', node.uuid, instance=instance) | |
| def reboot(self, context, instance, network_info, reboot_type, block_device_info=None, bad_volumes_callback=None): | |
| 'Reboot the specified instance.\n\n NOTE: Unlike the libvirt driver, this method does not delete\n and recreate the instance; it preserves local state.\n\n :param context: The security context.\n :param instance: The instance object.\n :param network_info: Instance network information. Ignored by\n this driver.\n :param reboot_type: Either a HARD or SOFT reboot.\n :param block_device_info: Info pertaining to attached volumes.\n Ignored by this driver.\n :param bad_volumes_callback: Function to handle any bad volumes\n encountered. Ignored by this driver.\n\n ' | |
| LOG.debug('Reboot(type %s) called for instance', reboot_type, instance=instance) | |
| node = self._validate_instance_and_node(instance) | |
| hard = True | |
| if (reboot_type == 'SOFT'): | |
| try: | |
| self.ironicclient.call('node.set_power_state', node.uuid, 'reboot', soft=True) | |
| hard = False | |
| except ironic.exc.BadRequest as exc: | |
| LOG.info('Soft reboot is not supported by ironic hardware driver. Falling back to hard reboot: %s', exc, instance=instance) | |
| if hard: | |
| self.ironicclient.call('node.set_power_state', node.uuid, 'reboot') | |
| timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_power_state, instance, 'reboot') | |
| timer.start(interval=CONF.ironic.api_retry_interval).wait() | |
| LOG.info('Successfully rebooted(type %(type)s) Ironic node %(node)s', {'type': ('HARD' if hard else 'SOFT'), 'node': node.uuid}, instance=instance) | |
| def power_off(self, instance, timeout=0, retry_interval=0): | |
| 'Power off the specified instance.\n\n NOTE: Unlike the libvirt driver, this method does not delete\n and recreate the instance; it preserves local state.\n\n :param instance: The instance object.\n :param timeout: time to wait for node to shutdown. If it is set,\n soft power off is attempted before hard power off.\n :param retry_interval: How often to signal node while waiting\n for it to shutdown. Ignored by this driver. Retrying depends on\n Ironic hardware driver.\n ' | |
| LOG.debug('Power off called for instance', instance=instance) | |
| node = self._validate_instance_and_node(instance) | |
| if timeout: | |
| try: | |
| self.ironicclient.call('node.set_power_state', node.uuid, 'off', soft=True, timeout=timeout) | |
| timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_power_state, instance, 'soft power off') | |
| timer.start(interval=CONF.ironic.api_retry_interval).wait() | |
| node = self._validate_instance_and_node(instance) | |
| if (node.power_state == ironic_states.POWER_OFF): | |
| LOG.info('Successfully soft powered off Ironic node %s', node.uuid, instance=instance) | |
| return | |
| LOG.info('Failed to soft power off instance %(instance)s on baremetal node %(node)s within the required timeout %(timeout)d seconds due to error: %(reason)s. Attempting hard power off.', {'instance': instance.uuid, 'timeout': timeout, 'node': node.uuid, 'reason': node.last_error}, instance=instance) | |
| except ironic.exc.ClientException as e: | |
| LOG.info('Failed to soft power off instance %(instance)s on baremetal node %(node)s due to error: %(reason)s. Attempting hard power off.', {'instance': instance.uuid, 'node': node.uuid, 'reason': e}, instance=instance) | |
| self.ironicclient.call('node.set_power_state', node.uuid, 'off') | |
| timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_power_state, instance, 'power off') | |
| timer.start(interval=CONF.ironic.api_retry_interval).wait() | |
| LOG.info('Successfully hard powered off Ironic node %s', node.uuid, instance=instance) | |
| def power_on(self, context, instance, network_info, block_device_info=None): | |
| 'Power on the specified instance.\n\n NOTE: Unlike the libvirt driver, this method does not delete\n and recreate the instance; it preserves local state.\n\n :param context: The security context.\n :param instance: The instance object.\n :param network_info: Instance network information. Ignored by\n this driver.\n :param block_device_info: Instance block device\n information. Ignored by this driver.\n\n ' | |
| LOG.debug('Power on called for instance', instance=instance) | |
| node = self._validate_instance_and_node(instance) | |
| self.ironicclient.call('node.set_power_state', node.uuid, 'on') | |
| timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_power_state, instance, 'power on') | |
| timer.start(interval=CONF.ironic.api_retry_interval).wait() | |
| LOG.info('Successfully powered on Ironic node %s', node.uuid, instance=instance) | |
| def trigger_crash_dump(self, instance): | |
| 'Trigger crash dump mechanism on the given instance.\n\n Stalling instances can be triggered to dump the crash data. How the\n guest OS reacts in details, depends on the configuration of it.\n\n :param instance: The instance where the crash dump should be triggered.\n\n :return: None\n ' | |
| LOG.debug('Trigger crash dump called for instance', instance=instance) | |
| node = self._validate_instance_and_node(instance) | |
| self.ironicclient.call('node.inject_nmi', node.uuid) | |
| LOG.info('Successfully triggered crash dump into Ironic node %s', node.uuid, instance=instance) | |
| def refresh_security_group_rules(self, security_group_id): | |
| 'Refresh security group rules from data store.\n\n Invoked when security group rules are updated.\n\n :param security_group_id: The security group id.\n\n ' | |
| self.firewall_driver.refresh_security_group_rules(security_group_id) | |
| def refresh_instance_security_rules(self, instance): | |
| 'Refresh security group rules from data store.\n\n Gets called when an instance gets added to or removed from\n the security group the instance is a member of or if the\n group gains or loses a rule.\n\n :param instance: The instance object.\n\n ' | |
| self.firewall_driver.refresh_instance_security_rules(instance) | |
| def ensure_filtering_rules_for_instance(self, instance, network_info): | |
| 'Set up filtering rules.\n\n :param instance: The instance object.\n :param network_info: Instance network information.\n\n ' | |
| self.firewall_driver.setup_basic_filtering(instance, network_info) | |
| self.firewall_driver.prepare_instance_filter(instance, network_info) | |
| def unfilter_instance(self, instance, network_info): | |
| 'Stop filtering instance.\n\n :param instance: The instance object.\n :param network_info: Instance network information.\n\n ' | |
| self.firewall_driver.unfilter_instance(instance, network_info) | |
| def _plug_vifs(self, node, instance, network_info): | |
| network_info_str = str(network_info) | |
| LOG.debug('plug: instance_uuid=%(uuid)s vif=%(network_info)s', {'uuid': instance.uuid, 'network_info': network_info_str}) | |
| for vif in network_info: | |
| port_id = six.text_type(vif['id']) | |
| try: | |
| self.ironicclient.call('node.vif_attach', node.uuid, port_id, retry_on_conflict=False) | |
| except ironic.exc.BadRequest as e: | |
| msg = (_('Cannot attach VIF %(vif)s to the node %(node)s due to error: %(err)s') % {'vif': port_id, 'node': node.uuid, 'err': e}) | |
| LOG.error(msg) | |
| raise exception.VirtualInterfacePlugException(msg) | |
| except ironic.exc.Conflict: | |
| pass | |
| def _unplug_vifs(self, node, instance, network_info): | |
| network_info_str = str(network_info) | |
| LOG.debug('unplug: instance_uuid=%(uuid)s vif=%(network_info)s', {'uuid': instance.uuid, 'network_info': network_info_str}) | |
| if (not network_info): | |
| return | |
| for vif in network_info: | |
| port_id = six.text_type(vif['id']) | |
| try: | |
| self.ironicclient.call('node.vif_detach', node.uuid, port_id) | |
| except ironic.exc.BadRequest: | |
| LOG.debug("VIF %(vif)s isn't attached to Ironic node %(node)s", {'vif': port_id, 'node': node.uuid}) | |
| def plug_vifs(self, instance, network_info): | |
| 'Plug VIFs into networks.\n\n :param instance: The instance object.\n :param network_info: Instance network information.\n\n ' | |
| node = self._get_node(instance.node) | |
| self._plug_vifs(node, instance, network_info) | |
| def unplug_vifs(self, instance, network_info): | |
| 'Unplug VIFs from networks.\n\n :param instance: The instance object.\n :param network_info: Instance network information.\n\n ' | |
| node = self._get_node(instance.node) | |
| self._unplug_vifs(node, instance, network_info) | |
| def attach_interface(self, context, instance, image_meta, vif): | |
| 'Use hotplug to add a network interface to a running instance.\n The counter action to this is :func:`detach_interface`.\n\n :param context: The request context.\n :param nova.objects.instance.Instance instance:\n The instance which will get an additional network interface.\n :param nova.objects.ImageMeta image_meta:\n The metadata of the image of the instance.\n :param nova.network.model.VIF vif:\n The object which has the information about the interface to attach.\n :raise nova.exception.NovaException: If the attach fails.\n :returns: None\n ' | |
| self.plug_vifs(instance, [vif]) | |
| def detach_interface(self, context, instance, vif): | |
| 'Use hotunplug to remove a network interface from a running instance.\n The counter action to this is :func:`attach_interface`.\n\n :param context: The request context.\n :param nova.objects.instance.Instance instance:\n The instance which gets a network interface removed.\n :param nova.network.model.VIF vif:\n The object which has the information about the interface to detach.\n :raise nova.exception.NovaException: If the detach fails.\n :returns: None\n ' | |
| self.unplug_vifs(instance, [vif]) | |
| def rebuild(self, context, instance, image_meta, injected_files, admin_password, bdms, detach_block_devices, attach_block_devices, network_info=None, recreate=False, block_device_info=None, preserve_ephemeral=False): | |
| "Rebuild/redeploy an instance.\n\n This version of rebuild() allows for supporting the option to\n preserve the ephemeral partition. We cannot call spawn() from\n here because it will attempt to set the instance_uuid value\n again, which is not allowed by the Ironic API. It also requires\n the instance to not have an 'active' provision state, but we\n cannot safely change that. Given that, we implement only the\n portions of spawn() we need within rebuild().\n\n :param context: The security context.\n :param instance: The instance object.\n :param image_meta: Image object returned by nova.image.glance\n that defines the image from which to boot this instance. Ignored\n by this driver.\n :param injected_files: User files to inject into instance. Ignored\n by this driver.\n :param admin_password: Administrator password to set in\n instance. Ignored by this driver.\n :param bdms: block-device-mappings to use for rebuild. Ignored\n by this driver.\n :param detach_block_devices: function to detach block devices. See\n nova.compute.manager.ComputeManager:_rebuild_default_impl for\n usage. Ignored by this driver.\n :param attach_block_devices: function to attach block devices. See\n nova.compute.manager.ComputeManager:_rebuild_default_impl for\n usage. Ignored by this driver.\n :param network_info: Instance network information. Ignored by\n this driver.\n :param recreate: Boolean value; if True the instance is\n recreated on a new hypervisor - all the cleanup of old state is\n skipped. Ignored by this driver.\n :param block_device_info: Instance block device\n information. Ignored by this driver.\n :param preserve_ephemeral: Boolean value; if True the ephemeral\n must be preserved on rebuild.\n\n " | |
| LOG.debug('Rebuild called for instance', instance=instance) | |
| instance.task_state = task_states.REBUILD_SPAWNING | |
| instance.save(expected_task_state=[task_states.REBUILDING]) | |
| node_uuid = instance.node | |
| node = self._get_node(node_uuid) | |
| self._add_instance_info_to_node(node, instance, image_meta, instance.flavor, preserve_ephemeral) | |
| try: | |
| self.ironicclient.call('node.set_provision_state', node_uuid, ironic_states.REBUILD) | |
| except (exception.NovaException, ironic.exc.InternalServerError, ironic.exc.BadRequest) as e: | |
| msg = (_('Failed to request Ironic to rebuild instance %(inst)s: %(reason)s') % {'inst': instance.uuid, 'reason': six.text_type(e)}) | |
| raise exception.InstanceDeployFailure(msg) | |
| timer = loopingcall.FixedIntervalLoopingCall(self._wait_for_active, instance) | |
| timer.start(interval=CONF.ironic.api_retry_interval).wait() | |
| LOG.info('Instance was successfully rebuilt', instance=instance) | |
| def network_binding_host_id(self, context, instance): | |
| "Get host ID to associate with network ports.\n\n This defines the binding:host_id parameter to the port-create calls for\n Neutron. If using the neutron network interface (separate networks for\n the control plane and tenants), return None here to indicate that the\n port should not yet be bound; Ironic will make a port-update call to\n Neutron later to tell Neutron to bind the port.\n\n NOTE: the late binding is important for security. If an ML2 mechanism\n manages to connect the tenant network to the baremetal machine before\n deployment is done (e.g. port-create time), then the tenant potentially\n has access to the deploy agent, which may contain firmware blobs or\n secrets. ML2 mechanisms may be able to connect the port without the\n switchport info that comes from ironic, if they store that switchport\n info for some reason. As such, we should *never* pass binding:host_id\n in the port-create call when using the 'neutron' network_interface,\n because a null binding:host_id indicates to Neutron that it should\n not connect the port yet.\n\n :param context: request context\n :param instance: nova.objects.instance.Instance that the network\n ports will be associated with\n :returns: None\n " | |
| return None | |
| def _get_node_console_with_reset(self, instance): | |
| "Acquire console information for an instance.\n\n If the console is enabled, the console will be re-enabled\n before returning.\n\n :param instance: nova instance\n :return: a dictionary with below values\n { 'node': ironic node\n 'console_info': node console info }\n :raise ConsoleNotAvailable: if console is unavailable\n for the instance\n " | |
| node = self._validate_instance_and_node(instance) | |
| node_uuid = node.uuid | |
| def _get_console(): | |
| 'Request ironicclient to acquire node console.' | |
| try: | |
| return self.ironicclient.call('node.get_console', node_uuid) | |
| except (exception.NovaException, ironic.exc.InternalServerError, ironic.exc.BadRequest) as e: | |
| LOG.error('Failed to acquire console information for instance %(inst)s: %(reason)s', {'inst': instance.uuid, 'reason': e}) | |
| raise exception.ConsoleNotAvailable() | |
| def _wait_state(state): | |
| 'Wait for the expected console mode to be set on node.' | |
| console = _get_console() | |
| if (console['console_enabled'] == state): | |
| raise loopingcall.LoopingCallDone(retvalue=console) | |
| _log_ironic_polling('set console mode', node, instance) | |
| return False | |
| def _enable_console(mode): | |
| 'Request ironicclient to enable/disable node console.' | |
| try: | |
| self.ironicclient.call('node.set_console_mode', node_uuid, mode) | |
| except (exception.NovaException, ironic.exc.InternalServerError, ironic.exc.BadRequest) as e: | |
| LOG.error('Failed to set console mode to "%(mode)s" for instance %(inst)s: %(reason)s', {'mode': mode, 'inst': instance.uuid, 'reason': e}) | |
| raise exception.ConsoleNotAvailable() | |
| try: | |
| timer = loopingcall.BackOffLoopingCall(_wait_state, state=mode) | |
| return timer.start(starting_interval=_CONSOLE_STATE_CHECKING_INTERVAL, timeout=CONF.ironic.serial_console_state_timeout, jitter=0.5).wait() | |
| except loopingcall.LoopingCallTimeOut: | |
| LOG.error('Timeout while waiting for console mode to be set to "%(mode)s" on node %(node)s', {'mode': mode, 'node': node_uuid}) | |
| raise exception.ConsoleNotAvailable() | |
| console = _get_console() | |
| if console['console_enabled']: | |
| try: | |
| _enable_console(False) | |
| console = _enable_console(True) | |
| except exception.ConsoleNotAvailable: | |
| console = _enable_console(True) | |
| if console['console_enabled']: | |
| return {'node': node, 'console_info': console['console_info']} | |
| else: | |
| LOG.debug('Console is disabled for instance %s', instance.uuid) | |
| raise exception.ConsoleNotAvailable() | |
| def get_serial_console(self, context, instance): | |
| 'Acquire serial console information.\n\n :param context: request context\n :param instance: nova instance\n :return: ConsoleSerial object\n :raise ConsoleTypeUnavailable: if serial console is unavailable\n for the instance\n ' | |
| LOG.debug('Getting serial console', instance=instance) | |
| try: | |
| result = self._get_node_console_with_reset(instance) | |
| except exception.ConsoleNotAvailable: | |
| raise exception.ConsoleTypeUnavailable(console_type='serial') | |
| node = result['node'] | |
| console_info = result['console_info'] | |
| if (console_info['type'] != 'socat'): | |
| LOG.warning('Console type "%(type)s" (of ironic node %(node)s) does not support Nova serial console', {'type': console_info['type'], 'node': node.uuid}, instance=instance) | |
| raise exception.ConsoleTypeUnavailable(console_type='serial') | |
| url = urlparse.urlparse(console_info['url']) | |
| try: | |
| scheme = url.scheme | |
| hostname = url.hostname | |
| port = url.port | |
| if (not (scheme and hostname and port)): | |
| raise AssertionError() | |
| except (ValueError, AssertionError): | |
| LOG.error('Invalid Socat console URL "%(url)s" (ironic node %(node)s)', {'url': console_info['url'], 'node': node.uuid}, instance=instance) | |
| raise exception.ConsoleTypeUnavailable(console_type='serial') | |
| if (scheme == 'tcp'): | |
| return console_type.ConsoleSerial(host=hostname, port=port) | |
| else: | |
| LOG.warning('Socat serial console only supports "tcp". This URL is "%(url)s" (ironic node %(node)s).', {'url': console_info['url'], 'node': node.uuid}, instance=instance) | |
| raise exception.ConsoleTypeUnavailable(console_type='serial') | |
| @property | |
| def need_legacy_block_device_info(self): | |
| return False | |
| def get_volume_connector(self, instance): | |
| "Get connector information for the instance for attaching to volumes.\n\n Connector information is a dictionary representing the hardware\n information that will be making the connection. This information\n consists of properties for protocols supported by the hardware.\n If the hardware supports iSCSI protocol, iSCSI initiator IQN is\n included as follows::\n\n {\n 'ip': ip,\n 'initiator': initiator,\n 'host': hostname\n }\n\n :param instance: nova instance\n :returns: A connector information dictionary\n " | |
| node = self.ironicclient.call('node.get', instance.node) | |
| properties = self._parse_node_properties(node) | |
| connectors = self.ironicclient.call('node.list_volume_connectors', instance.node, detail=True) | |
| values = {} | |
| for conn in connectors: | |
| values.setdefault(conn.type, []).append(conn.connector_id) | |
| props = {} | |
| if values.get('ip'): | |
| props['ip'] = props['host'] = values['ip'][0] | |
| if values.get('iqn'): | |
| props['initiator'] = values['iqn'][0] | |
| if values.get('wwpn'): | |
| props['wwpns'] = values['wwpn'] | |
| if values.get('wwnn'): | |
| props['wwnns'] = values['wwnn'] | |
| props['platform'] = properties.get('cpu_arch') | |
| props['os_type'] = 'baremetal' | |
| props['multipath'] = False | |
| return props | |
Xet Storage Details
- Size:
- 59.7 kB
- Xet hash:
- 5905a61fd5bc11413653fe51570aa33225815b15575cf838c74cb4ab9ebe4f9e
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.