OpenStack Compute (Nova)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

8684 lines
411KB

  1. # Copyright 2010 United States Government as represented by the
  2. # Administrator of the National Aeronautics and Space Administration.
  3. # Copyright 2011 Justin Santa Barbara
  4. # All Rights Reserved.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  7. # not use this file except in compliance with the License. You may obtain
  8. # a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  14. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  15. # License for the specific language governing permissions and limitations
  16. # under the License.
  17. """Handles all processes relating to instances (guest vms).
  18. The :py:class:`ComputeManager` class is a :py:class:`nova.manager.Manager` that
  19. handles RPC calls relating to creating instances. It is responsible for
  20. building a disk image, launching it via the underlying virtualization driver,
  21. responding to calls to check its state, attaching persistent storage, and
  22. terminating it.
  23. """
  24. import base64
  25. import binascii
  26. # If py2, concurrent.futures comes from the futures library otherwise it
  27. # comes from the py3 standard library.
  28. from concurrent import futures
  29. import contextlib
  30. import copy
  31. import functools
  32. import inspect
  33. import sys
  34. import time
  35. import traceback
  36. from cinderclient import exceptions as cinder_exception
  37. from cursive import exception as cursive_exception
  38. import eventlet.event
  39. from eventlet import greenthread
  40. import eventlet.semaphore
  41. import eventlet.timeout
  42. from keystoneauth1 import exceptions as keystone_exception
  43. from oslo_log import log as logging
  44. import oslo_messaging as messaging
  45. from oslo_serialization import jsonutils
  46. from oslo_service import loopingcall
  47. from oslo_service import periodic_task
  48. from oslo_utils import excutils
  49. from oslo_utils import strutils
  50. from oslo_utils import timeutils
  51. import six
  52. from six.moves import range
  53. from nova import block_device
  54. from nova.cells import rpcapi as cells_rpcapi
  55. from nova import compute
  56. from nova.compute import build_results
  57. from nova.compute import claims
  58. from nova.compute import power_state
  59. from nova.compute import resource_tracker
  60. from nova.compute import rpcapi as compute_rpcapi
  61. from nova.compute import task_states
  62. from nova.compute import utils as compute_utils
  63. from nova.compute.utils import wrap_instance_event
  64. from nova.compute import vm_states
  65. from nova import conductor
  66. import nova.conf
  67. from nova.console import rpcapi as console_rpcapi
  68. import nova.context
  69. from nova import exception
  70. from nova import exception_wrapper
  71. from nova import hooks
  72. from nova.i18n import _
  73. from nova import image
  74. from nova import manager
  75. from nova import network
  76. from nova.network import base_api as base_net_api
  77. from nova.network import model as network_model
  78. from nova.network.security_group import openstack_driver
  79. from nova import objects
  80. from nova.objects import base as obj_base
  81. from nova.objects import fields
  82. from nova.objects import instance as obj_instance
  83. from nova.objects import migrate_data as migrate_data_obj
  84. from nova.pci import whitelist
  85. from nova import rpc
  86. from nova import safe_utils
  87. from nova.scheduler import client as scheduler_client
  88. from nova.scheduler import utils as scheduler_utils
  89. from nova import utils
  90. from nova.virt import block_device as driver_block_device
  91. from nova.virt import configdrive
  92. from nova.virt import driver
  93. from nova.virt import event as virtevent
  94. from nova.virt import storage_users
  95. from nova.virt import virtapi
  96. from nova.volume import cinder
  97. CONF = nova.conf.CONF
  98. LOG = logging.getLogger(__name__)
  99. get_notifier = functools.partial(rpc.get_notifier, service='compute')
  100. wrap_exception = functools.partial(exception_wrapper.wrap_exception,
  101. get_notifier=get_notifier,
  102. binary='nova-compute')
  103. @contextlib.contextmanager
  104. def errors_out_migration_ctxt(migration):
  105. """Context manager to error out migration on failure."""
  106. try:
  107. yield
  108. except Exception:
  109. with excutils.save_and_reraise_exception():
  110. if migration:
  111. # We may have been passed None for our migration if we're
  112. # receiving from an older client. The migration will be
  113. # errored via the legacy path.
  114. migration.status = 'error'
  115. try:
  116. with migration.obj_as_admin():
  117. migration.save()
  118. except Exception:
  119. LOG.debug(
  120. 'Error setting migration status for instance %s.',
  121. migration.instance_uuid, exc_info=True)
  122. @utils.expects_func_args('migration')
  123. def errors_out_migration(function):
  124. """Decorator to error out migration on failure."""
  125. @functools.wraps(function)
  126. def decorated_function(self, context, *args, **kwargs):
  127. wrapped_func = safe_utils.get_wrapped_function(function)
  128. keyed_args = inspect.getcallargs(wrapped_func, self, context,
  129. *args, **kwargs)
  130. migration = keyed_args['migration']
  131. with errors_out_migration_ctxt(migration):
  132. return function(self, context, *args, **kwargs)
  133. return decorated_function
  134. @utils.expects_func_args('instance')
  135. def reverts_task_state(function):
  136. """Decorator to revert task_state on failure."""
  137. @functools.wraps(function)
  138. def decorated_function(self, context, *args, **kwargs):
  139. try:
  140. return function(self, context, *args, **kwargs)
  141. except exception.UnexpectedTaskStateError as e:
  142. # Note(maoy): unexpected task state means the current
  143. # task is preempted. Do not clear task state in this
  144. # case.
  145. with excutils.save_and_reraise_exception():
  146. LOG.info("Task possibly preempted: %s",
  147. e.format_message())
  148. except Exception:
  149. with excutils.save_and_reraise_exception():
  150. wrapped_func = safe_utils.get_wrapped_function(function)
  151. keyed_args = inspect.getcallargs(wrapped_func, self, context,
  152. *args, **kwargs)
  153. # NOTE(mriedem): 'instance' must be in keyed_args because we
  154. # have utils.expects_func_args('instance') decorating this
  155. # method.
  156. instance = keyed_args['instance']
  157. original_task_state = instance.task_state
  158. try:
  159. self._instance_update(context, instance, task_state=None)
  160. LOG.info("Successfully reverted task state from %s on "
  161. "failure for instance.",
  162. original_task_state, instance=instance)
  163. except exception.InstanceNotFound:
  164. # We might delete an instance that failed to build shortly
  165. # after it errored out this is an expected case and we
  166. # should not trace on it.
  167. pass
  168. except Exception as e:
  169. LOG.warning("Failed to revert task state for instance. "
  170. "Error: %s", e, instance=instance)
  171. return decorated_function
  172. @utils.expects_func_args('instance')
  173. def wrap_instance_fault(function):
  174. """Wraps a method to catch exceptions related to instances.
  175. This decorator wraps a method to catch any exceptions having to do with
  176. an instance that may get thrown. It then logs an instance fault in the db.
  177. """
  178. @functools.wraps(function)
  179. def decorated_function(self, context, *args, **kwargs):
  180. try:
  181. return function(self, context, *args, **kwargs)
  182. except exception.InstanceNotFound:
  183. raise
  184. except Exception as e:
  185. # NOTE(gtt): If argument 'instance' is in args rather than kwargs,
  186. # we will get a KeyError exception which will cover up the real
  187. # exception. So, we update kwargs with the values from args first.
  188. # then, we can get 'instance' from kwargs easily.
  189. kwargs.update(dict(zip(function.__code__.co_varnames[2:], args)))
  190. with excutils.save_and_reraise_exception():
  191. compute_utils.add_instance_fault_from_exc(context,
  192. kwargs['instance'], e, sys.exc_info())
  193. return decorated_function
  194. @utils.expects_func_args('image_id', 'instance')
  195. def delete_image_on_error(function):
  196. """Used for snapshot related method to ensure the image created in
  197. compute.api is deleted when an error occurs.
  198. """
  199. @functools.wraps(function)
  200. def decorated_function(self, context, image_id, instance,
  201. *args, **kwargs):
  202. try:
  203. return function(self, context, image_id, instance,
  204. *args, **kwargs)
  205. except Exception:
  206. with excutils.save_and_reraise_exception():
  207. LOG.debug("Cleaning up image %s", image_id,
  208. exc_info=True, instance=instance)
  209. try:
  210. self.image_api.delete(context, image_id)
  211. except exception.ImageNotFound:
  212. # Since we're trying to cleanup an image, we don't care if
  213. # if it's already gone.
  214. pass
  215. except Exception:
  216. LOG.exception("Error while trying to clean up image %s",
  217. image_id, instance=instance)
  218. return decorated_function
  219. # TODO(danms): Remove me after Icehouse
  220. # TODO(alaski): Actually remove this after Newton, assuming a major RPC bump
  221. # NOTE(mikal): if the method being decorated has more than one decorator, then
  222. # put this one first. Otherwise the various exception handling decorators do
  223. # not function correctly.
  224. def object_compat(function):
  225. """Wraps a method that expects a new-world instance
  226. This provides compatibility for callers passing old-style dict
  227. instances.
  228. """
  229. @functools.wraps(function)
  230. def decorated_function(self, context, *args, **kwargs):
  231. def _load_instance(instance_or_dict):
  232. if isinstance(instance_or_dict, dict):
  233. # try to get metadata and system_metadata for most cases but
  234. # only attempt to load those if the db instance already has
  235. # those fields joined
  236. metas = [meta for meta in ('metadata', 'system_metadata')
  237. if meta in instance_or_dict]
  238. instance = objects.Instance._from_db_object(
  239. context, objects.Instance(), instance_or_dict,
  240. expected_attrs=metas)
  241. instance._context = context
  242. return instance
  243. return instance_or_dict
  244. try:
  245. kwargs['instance'] = _load_instance(kwargs['instance'])
  246. except KeyError:
  247. args = (_load_instance(args[0]),) + args[1:]
  248. migration = kwargs.get('migration')
  249. if isinstance(migration, dict):
  250. migration = objects.Migration._from_db_object(
  251. context.elevated(), objects.Migration(),
  252. migration)
  253. kwargs['migration'] = migration
  254. return function(self, context, *args, **kwargs)
  255. return decorated_function
  256. class InstanceEvents(object):
  257. def __init__(self):
  258. self._events = {}
  259. @staticmethod
  260. def _lock_name(instance):
  261. return '%s-%s' % (instance.uuid, 'events')
  262. def prepare_for_instance_event(self, instance, name, tag):
  263. """Prepare to receive an event for an instance.
  264. This will register an event for the given instance that we will
  265. wait on later. This should be called before initiating whatever
  266. action will trigger the event. The resulting eventlet.event.Event
  267. object should be wait()'d on to ensure completion.
  268. :param instance: the instance for which the event will be generated
  269. :param name: the name of the event we're expecting
  270. :param tag: the tag associated with the event we're expecting
  271. :returns: an event object that should be wait()'d on
  272. """
  273. if self._events is None:
  274. # NOTE(danms): We really should have a more specific error
  275. # here, but this is what we use for our default error case
  276. raise exception.NovaException('In shutdown, no new events '
  277. 'can be scheduled')
  278. @utils.synchronized(self._lock_name(instance))
  279. def _create_or_get_event():
  280. instance_events = self._events.setdefault(instance.uuid, {})
  281. return instance_events.setdefault((name, tag),
  282. eventlet.event.Event())
  283. LOG.debug('Preparing to wait for external event %(name)s-%(tag)s',
  284. {'name': name, 'tag': tag}, instance=instance)
  285. return _create_or_get_event()
  286. def pop_instance_event(self, instance, event):
  287. """Remove a pending event from the wait list.
  288. This will remove a pending event from the wait list so that it
  289. can be used to signal the waiters to wake up.
  290. :param instance: the instance for which the event was generated
  291. :param event: the nova.objects.external_event.InstanceExternalEvent
  292. that describes the event
  293. :returns: the eventlet.event.Event object on which the waiters
  294. are blocked
  295. """
  296. no_events_sentinel = object()
  297. no_matching_event_sentinel = object()
  298. @utils.synchronized(self._lock_name(instance))
  299. def _pop_event():
  300. if self._events is None:
  301. LOG.debug('Unexpected attempt to pop events during shutdown',
  302. instance=instance)
  303. return no_events_sentinel
  304. events = self._events.get(instance.uuid)
  305. if not events:
  306. return no_events_sentinel
  307. _event = events.pop((event.name, event.tag), None)
  308. if not events:
  309. del self._events[instance.uuid]
  310. if _event is None:
  311. return no_matching_event_sentinel
  312. return _event
  313. result = _pop_event()
  314. if result is no_events_sentinel:
  315. LOG.debug('No waiting events found dispatching %(event)s',
  316. {'event': event.key},
  317. instance=instance)
  318. return None
  319. elif result is no_matching_event_sentinel:
  320. LOG.debug('No event matching %(event)s in %(events)s',
  321. {'event': event.key,
  322. 'events': self._events.get(instance.uuid, {}).keys()},
  323. instance=instance)
  324. return None
  325. else:
  326. return result
  327. def clear_events_for_instance(self, instance):
  328. """Remove all pending events for an instance.
  329. This will remove all events currently pending for an instance
  330. and return them (indexed by event name).
  331. :param instance: the instance for which events should be purged
  332. :returns: a dictionary of {event_name: eventlet.event.Event}
  333. """
  334. @utils.synchronized(self._lock_name(instance))
  335. def _clear_events():
  336. if self._events is None:
  337. LOG.debug('Unexpected attempt to clear events during shutdown',
  338. instance=instance)
  339. return dict()
  340. # NOTE(danms): We have historically returned the raw internal
  341. # format here, which is {event.key: [events, ...])} so just
  342. # trivially convert it here.
  343. return {'%s-%s' % k: e
  344. for k, e in self._events.pop(instance.uuid, {}).items()}
  345. return _clear_events()
  346. def cancel_all_events(self):
  347. if self._events is None:
  348. LOG.debug('Unexpected attempt to cancel events during shutdown.')
  349. return
  350. our_events = self._events
  351. # NOTE(danms): Block new events
  352. self._events = None
  353. for instance_uuid, events in our_events.items():
  354. for (name, tag), eventlet_event in events.items():
  355. LOG.debug('Canceling in-flight event %(name)s-%(tag)s for '
  356. 'instance %(instance_uuid)s',
  357. {'name': name,
  358. 'tag': tag,
  359. 'instance_uuid': instance_uuid})
  360. event = objects.InstanceExternalEvent(
  361. instance_uuid=instance_uuid,
  362. name=name, status='failed',
  363. tag=tag, data={})
  364. eventlet_event.send(event)
  365. class ComputeVirtAPI(virtapi.VirtAPI):
  366. def __init__(self, compute):
  367. super(ComputeVirtAPI, self).__init__()
  368. self._compute = compute
  369. def _default_error_callback(self, event_name, instance):
  370. raise exception.NovaException(_('Instance event failed'))
  371. @contextlib.contextmanager
  372. def wait_for_instance_event(self, instance, event_names, deadline=300,
  373. error_callback=None):
  374. """Plan to wait for some events, run some code, then wait.
  375. This context manager will first create plans to wait for the
  376. provided event_names, yield, and then wait for all the scheduled
  377. events to complete.
  378. Note that this uses an eventlet.timeout.Timeout to bound the
  379. operation, so callers should be prepared to catch that
  380. failure and handle that situation appropriately.
  381. If the event is not received by the specified timeout deadline,
  382. eventlet.timeout.Timeout is raised.
  383. If the event is received but did not have a 'completed'
  384. status, a NovaException is raised. If an error_callback is
  385. provided, instead of raising an exception as detailed above
  386. for the failure case, the callback will be called with the
  387. event_name and instance, and can return True to continue
  388. waiting for the rest of the events, False to stop processing,
  389. or raise an exception which will bubble up to the waiter.
  390. :param instance: The instance for which an event is expected
  391. :param event_names: A list of event names. Each element is a
  392. tuple of strings to indicate (name, tag),
  393. where name is required, but tag may be None.
  394. :param deadline: Maximum number of seconds we should wait for all
  395. of the specified events to arrive.
  396. :param error_callback: A function to be called if an event arrives
  397. """
  398. if error_callback is None:
  399. error_callback = self._default_error_callback
  400. events = {}
  401. for event_name in event_names:
  402. name, tag = event_name
  403. event_name = objects.InstanceExternalEvent.make_key(name, tag)
  404. try:
  405. events[event_name] = (
  406. self._compute.instance_events.prepare_for_instance_event(
  407. instance, name, tag))
  408. except exception.NovaException:
  409. error_callback(event_name, instance)
  410. # NOTE(danms): Don't wait for any of the events. They
  411. # should all be canceled and fired immediately below,
  412. # but don't stick around if not.
  413. deadline = 0
  414. yield
  415. with eventlet.timeout.Timeout(deadline):
  416. for event_name, event in events.items():
  417. actual_event = event.wait()
  418. if actual_event.status == 'completed':
  419. continue
  420. decision = error_callback(event_name, instance)
  421. if decision is False:
  422. break
  423. class ComputeManager(manager.Manager):
  424. """Manages the running instances from creation to destruction."""
  425. target = messaging.Target(version='5.0')
  426. def __init__(self, compute_driver=None, *args, **kwargs):
  427. """Load configuration options and connect to the hypervisor."""
  428. self.virtapi = ComputeVirtAPI(self)
  429. self.network_api = network.API()
  430. self.volume_api = cinder.API()
  431. self.image_api = image.API()
  432. self._last_host_check = 0
  433. self._last_bw_usage_poll = 0
  434. self._bw_usage_supported = True
  435. self._last_bw_usage_cell_update = 0
  436. self.compute_api = compute.API()
  437. self.compute_rpcapi = compute_rpcapi.ComputeAPI()
  438. self.conductor_api = conductor.API()
  439. self.compute_task_api = conductor.ComputeTaskAPI()
  440. self.is_neutron_security_groups = (
  441. openstack_driver.is_neutron_security_groups())
  442. self.cells_rpcapi = cells_rpcapi.CellsAPI()
  443. self.scheduler_client = scheduler_client.SchedulerClient()
  444. self.reportclient = self.scheduler_client.reportclient
  445. self._resource_tracker = None
  446. self.instance_events = InstanceEvents()
  447. self._sync_power_pool = eventlet.GreenPool(
  448. size=CONF.sync_power_state_pool_size)
  449. self._syncs_in_progress = {}
  450. self.send_instance_updates = (
  451. CONF.filter_scheduler.track_instance_changes)
  452. if CONF.max_concurrent_builds != 0:
  453. self._build_semaphore = eventlet.semaphore.Semaphore(
  454. CONF.max_concurrent_builds)
  455. else:
  456. self._build_semaphore = compute_utils.UnlimitedSemaphore()
  457. if max(CONF.max_concurrent_live_migrations, 0) != 0:
  458. self._live_migration_executor = futures.ThreadPoolExecutor(
  459. max_workers=CONF.max_concurrent_live_migrations)
  460. else:
  461. # Starting in python 3.5, this is technically bounded, but it's
  462. # ncpu * 5 which is probably much higher than anyone would sanely
  463. # use for concurrently running live migrations.
  464. self._live_migration_executor = futures.ThreadPoolExecutor()
  465. # This is a dict, keyed by instance uuid, to a two-item tuple of
  466. # migration object and Future for the queued live migration.
  467. self._waiting_live_migrations = {}
  468. super(ComputeManager, self).__init__(service_name="compute",
  469. *args, **kwargs)
  470. # NOTE(russellb) Load the driver last. It may call back into the
  471. # compute manager via the virtapi, so we want it to be fully
  472. # initialized before that happens.
  473. self.driver = driver.load_compute_driver(self.virtapi, compute_driver)
  474. self.use_legacy_block_device_info = \
  475. self.driver.need_legacy_block_device_info
  476. def reset(self):
  477. LOG.info('Reloading compute RPC API')
  478. compute_rpcapi.LAST_VERSION = None
  479. self.compute_rpcapi = compute_rpcapi.ComputeAPI()
  480. def _get_resource_tracker(self):
  481. if not self._resource_tracker:
  482. rt = resource_tracker.ResourceTracker(self.host, self.driver)
  483. self._resource_tracker = rt
  484. return self._resource_tracker
  485. def _update_resource_tracker(self, context, instance):
  486. """Let the resource tracker know that an instance has changed state."""
  487. if instance.host == self.host:
  488. rt = self._get_resource_tracker()
  489. rt.update_usage(context, instance, instance.node)
  490. def _instance_update(self, context, instance, **kwargs):
  491. """Update an instance in the database using kwargs as value."""
  492. for k, v in kwargs.items():
  493. setattr(instance, k, v)
  494. instance.save()
  495. self._update_resource_tracker(context, instance)
  496. def _nil_out_instance_obj_host_and_node(self, instance):
  497. # NOTE(jwcroppe): We don't do instance.save() here for performance
  498. # reasons; a call to this is expected to be immediately followed by
  499. # another call that does instance.save(), thus avoiding two writes
  500. # to the database layer.
  501. instance.host = None
  502. instance.node = None
  503. # If the instance is not on a host, it's not in an aggregate and
  504. # therefore is not in an availability zone.
  505. instance.availability_zone = None
  506. def _set_instance_obj_error_state(self, context, instance,
  507. clean_task_state=False):
  508. try:
  509. instance.vm_state = vm_states.ERROR
  510. if clean_task_state:
  511. instance.task_state = None
  512. instance.save()
  513. except exception.InstanceNotFound:
  514. LOG.debug('Instance has been destroyed from under us while '
  515. 'trying to set it to ERROR', instance=instance)
  516. def _get_instances_on_driver(self, context, filters=None):
  517. """Return a list of instance records for the instances found
  518. on the hypervisor which satisfy the specified filters. If filters=None
  519. return a list of instance records for all the instances found on the
  520. hypervisor.
  521. """
  522. if not filters:
  523. filters = {}
  524. try:
  525. driver_uuids = self.driver.list_instance_uuids()
  526. if len(driver_uuids) == 0:
  527. # Short circuit, don't waste a DB call
  528. return objects.InstanceList()
  529. filters['uuid'] = driver_uuids
  530. local_instances = objects.InstanceList.get_by_filters(
  531. context, filters, use_slave=True)
  532. return local_instances
  533. except NotImplementedError:
  534. pass
  535. # The driver doesn't support uuids listing, so we'll have
  536. # to brute force.
  537. driver_instances = self.driver.list_instances()
  538. # NOTE(mjozefcz): In this case we need to apply host filter.
  539. # Without this all instance data would be fetched from db.
  540. filters['host'] = self.host
  541. instances = objects.InstanceList.get_by_filters(context, filters,
  542. use_slave=True)
  543. name_map = {instance.name: instance for instance in instances}
  544. local_instances = []
  545. for driver_instance in driver_instances:
  546. instance = name_map.get(driver_instance)
  547. if not instance:
  548. continue
  549. local_instances.append(instance)
  550. return local_instances
  551. def _destroy_evacuated_instances(self, context):
  552. """Destroys evacuated instances.
  553. While nova-compute was down, the instances running on it could be
  554. evacuated to another host. This method looks for evacuation migration
  555. records where this is the source host and which were either started
  556. (accepted), in-progress (pre-migrating) or migrated (done). From those
  557. migration records, local instances reported by the hypervisor are
  558. compared to the instances for the migration records and those local
  559. guests are destroyed, along with instance allocation records in
  560. Placement for this node.
  561. Then allocations are removed from Placement for every instance that is
  562. evacuated from this host regardless if the instance is reported by the
  563. hypervisor or not.
  564. :param context: The request context
  565. :return: A dict keyed by instance uuid mapped to Migration objects
  566. for instances that were migrated away from this host
  567. """
  568. filters = {
  569. 'source_compute': self.host,
  570. # NOTE(mriedem): Migration records that have been accepted are
  571. # included in case the source node comes back up while instances
  572. # are being evacuated to another host. We don't want the same
  573. # instance being reported from multiple hosts.
  574. # NOTE(lyarwood): pre-migrating is also included here as the
  575. # source compute can come back online shortly after the RT
  576. # claims on the destination that in-turn moves the migration to
  577. # pre-migrating. If the evacuate fails on the destination host,
  578. # the user can rebuild the instance (in ERROR state) on the source
  579. # host.
  580. 'status': ['accepted', 'pre-migrating', 'done'],
  581. 'migration_type': 'evacuation',
  582. }
  583. with utils.temporary_mutation(context, read_deleted='yes'):
  584. evacuations = objects.MigrationList.get_by_filters(context,
  585. filters)
  586. if not evacuations:
  587. return {}
  588. evacuations = {mig.instance_uuid: mig for mig in evacuations}
  589. # The instances might be deleted in which case we need to avoid
  590. # InstanceNotFound being raised from lazy-loading fields on the
  591. # instances while cleaning up this host.
  592. read_deleted_context = context.elevated(read_deleted='yes')
  593. # TODO(mriedem): We could optimize by pre-loading the joined fields
  594. # we know we'll use, like info_cache and flavor. We can also replace
  595. # this with a generic solution: https://review.openstack.org/575190/
  596. local_instances = self._get_instances_on_driver(read_deleted_context)
  597. evacuated_local_instances = {inst.uuid: inst
  598. for inst in local_instances
  599. if inst.uuid in evacuations}
  600. for instance in evacuated_local_instances.values():
  601. LOG.info('Destroying instance as it has been evacuated from '
  602. 'this host but still exists in the hypervisor',
  603. instance=instance)
  604. try:
  605. network_info = self.network_api.get_instance_nw_info(
  606. context, instance)
  607. bdi = self._get_instance_block_device_info(context,
  608. instance)
  609. destroy_disks = not (self._is_instance_storage_shared(
  610. context, instance))
  611. except exception.InstanceNotFound:
  612. network_info = network_model.NetworkInfo()
  613. bdi = {}
  614. LOG.info('Instance has been marked deleted already, '
  615. 'removing it from the hypervisor.',
  616. instance=instance)
  617. # always destroy disks if the instance was deleted
  618. destroy_disks = True
  619. self.driver.destroy(context, instance,
  620. network_info,
  621. bdi, destroy_disks)
  622. # NOTE(gibi): We are called from init_host and at this point the
  623. # compute_nodes of the resource tracker has not been populated yet so
  624. # we cannot rely on the resource tracker here.
  625. compute_nodes = {}
  626. for instance_uuid, migration in evacuations.items():
  627. try:
  628. if instance_uuid in evacuated_local_instances:
  629. # Avoid the db call if we already have the instance loaded
  630. # above
  631. instance = evacuated_local_instances[instance_uuid]
  632. else:
  633. instance = objects.Instance.get_by_uuid(
  634. context, instance_uuid)
  635. except exception.InstanceNotFound:
  636. # The instance already deleted so we expect that every
  637. # allocation of that instance has already been cleaned up
  638. continue
  639. LOG.info('Cleaning up allocations of the instance as it has been '
  640. 'evacuated from this host',
  641. instance=instance)
  642. if migration.source_node not in compute_nodes:
  643. try:
  644. cn_uuid = objects.ComputeNode.get_by_host_and_nodename(
  645. context, self.host, migration.source_node).uuid
  646. compute_nodes[migration.source_node] = cn_uuid
  647. except exception.ComputeHostNotFound:
  648. LOG.error("Failed to clean allocation of evacuated "
  649. "instance as the source node %s is not found",
  650. migration.source_node, instance=instance)
  651. continue
  652. cn_uuid = compute_nodes[migration.source_node]
  653. # If the instance was deleted in the interim, assume its
  654. # allocations were properly cleaned up (either by its hosting
  655. # compute service or the API).
  656. if (not instance.deleted and
  657. not scheduler_utils.remove_allocation_from_compute(
  658. context, instance, cn_uuid, self.reportclient)):
  659. LOG.error("Failed to clean allocation of evacuated instance "
  660. "on the source node %s",
  661. cn_uuid, instance=instance)
  662. migration.status = 'completed'
  663. migration.save()
  664. return evacuations
  665. def _is_instance_storage_shared(self, context, instance, host=None):
  666. shared_storage = True
  667. data = None
  668. try:
  669. data = self.driver.check_instance_shared_storage_local(context,
  670. instance)
  671. if data:
  672. shared_storage = (self.compute_rpcapi.
  673. check_instance_shared_storage(context,
  674. instance, data, host=host))
  675. except NotImplementedError:
  676. LOG.debug('Hypervisor driver does not support '
  677. 'instance shared storage check, '
  678. 'assuming it\'s not on shared storage',
  679. instance=instance)
  680. shared_storage = False
  681. except Exception:
  682. LOG.exception('Failed to check if instance shared',
  683. instance=instance)
  684. finally:
  685. if data:
  686. self.driver.check_instance_shared_storage_cleanup(context,
  687. data)
  688. return shared_storage
  689. def _complete_partial_deletion(self, context, instance):
  690. """Complete deletion for instances in DELETED status but not marked as
  691. deleted in the DB
  692. """
  693. instance.destroy()
  694. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  695. context, instance.uuid)
  696. self._complete_deletion(context,
  697. instance,
  698. bdms)
  699. def _complete_deletion(self, context, instance, bdms):
  700. self._update_resource_tracker(context, instance)
  701. rt = self._get_resource_tracker()
  702. rt.reportclient.delete_allocation_for_instance(context, instance.uuid)
  703. self._notify_about_instance_usage(context, instance, "delete.end")
  704. compute_utils.notify_about_instance_action(context, instance,
  705. self.host, action=fields.NotificationAction.DELETE,
  706. phase=fields.NotificationPhase.END, bdms=bdms)
  707. self._clean_instance_console_tokens(context, instance)
  708. self._delete_scheduler_instance_info(context, instance.uuid)
  709. def _init_instance(self, context, instance):
  710. """Initialize this instance during service init."""
  711. # NOTE(danms): If the instance appears to not be owned by this
  712. # host, it may have been evacuated away, but skipped by the
  713. # evacuation cleanup code due to configuration. Thus, if that
  714. # is a possibility, don't touch the instance in any way, but
  715. # log the concern. This will help avoid potential issues on
  716. # startup due to misconfiguration.
  717. if instance.host != self.host:
  718. LOG.warning('Instance %(uuid)s appears to not be owned '
  719. 'by this host, but by %(host)s. Startup '
  720. 'processing is being skipped.',
  721. {'uuid': instance.uuid,
  722. 'host': instance.host})
  723. return
  724. # Instances that are shut down, or in an error state can not be
  725. # initialized and are not attempted to be recovered. The exception
  726. # to this are instances that are in RESIZE_MIGRATING or DELETING,
  727. # which are dealt with further down.
  728. if (instance.vm_state == vm_states.SOFT_DELETED or
  729. (instance.vm_state == vm_states.ERROR and
  730. instance.task_state not in
  731. (task_states.RESIZE_MIGRATING, task_states.DELETING))):
  732. LOG.debug("Instance is in %s state.",
  733. instance.vm_state, instance=instance)
  734. return
  735. if instance.vm_state == vm_states.DELETED:
  736. try:
  737. self._complete_partial_deletion(context, instance)
  738. except Exception:
  739. # we don't want that an exception blocks the init_host
  740. LOG.exception('Failed to complete a deletion',
  741. instance=instance)
  742. return
  743. if (instance.vm_state == vm_states.BUILDING or
  744. instance.task_state in [task_states.SCHEDULING,
  745. task_states.BLOCK_DEVICE_MAPPING,
  746. task_states.NETWORKING,
  747. task_states.SPAWNING]):
  748. # NOTE(dave-mcnally) compute stopped before instance was fully
  749. # spawned so set to ERROR state. This is safe to do as the state
  750. # may be set by the api but the host is not so if we get here the
  751. # instance has already been scheduled to this particular host.
  752. LOG.debug("Instance failed to spawn correctly, "
  753. "setting to ERROR state", instance=instance)
  754. self._set_instance_obj_error_state(
  755. context, instance, clean_task_state=True)
  756. return
  757. if (instance.vm_state in [vm_states.ACTIVE, vm_states.STOPPED] and
  758. instance.task_state in [task_states.REBUILDING,
  759. task_states.REBUILD_BLOCK_DEVICE_MAPPING,
  760. task_states.REBUILD_SPAWNING]):
  761. # NOTE(jichenjc) compute stopped before instance was fully
  762. # spawned so set to ERROR state. This is consistent to BUILD
  763. LOG.debug("Instance failed to rebuild correctly, "
  764. "setting to ERROR state", instance=instance)
  765. self._set_instance_obj_error_state(
  766. context, instance, clean_task_state=True)
  767. return
  768. if (instance.vm_state != vm_states.ERROR and
  769. instance.task_state in [task_states.IMAGE_SNAPSHOT_PENDING,
  770. task_states.IMAGE_PENDING_UPLOAD,
  771. task_states.IMAGE_UPLOADING,
  772. task_states.IMAGE_SNAPSHOT]):
  773. LOG.debug("Instance in transitional state %s at start-up "
  774. "clearing task state",
  775. instance.task_state, instance=instance)
  776. try:
  777. self._post_interrupted_snapshot_cleanup(context, instance)
  778. except Exception:
  779. # we don't want that an exception blocks the init_host
  780. LOG.exception('Failed to cleanup snapshot.', instance=instance)
  781. instance.task_state = None
  782. instance.save()
  783. if (instance.vm_state != vm_states.ERROR and
  784. instance.task_state in [task_states.RESIZE_PREP]):
  785. LOG.debug("Instance in transitional state %s at start-up "
  786. "clearing task state",
  787. instance['task_state'], instance=instance)
  788. instance.task_state = None
  789. instance.save()
  790. if instance.task_state == task_states.DELETING:
  791. try:
  792. LOG.info('Service started deleting the instance during '
  793. 'the previous run, but did not finish. Restarting'
  794. ' the deletion now.', instance=instance)
  795. instance.obj_load_attr('metadata')
  796. instance.obj_load_attr('system_metadata')
  797. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  798. context, instance.uuid)
  799. self._delete_instance(context, instance, bdms)
  800. except Exception:
  801. # we don't want that an exception blocks the init_host
  802. LOG.exception('Failed to complete a deletion',
  803. instance=instance)
  804. self._set_instance_obj_error_state(context, instance)
  805. return
  806. current_power_state = self._get_power_state(context, instance)
  807. try_reboot, reboot_type = self._retry_reboot(context, instance,
  808. current_power_state)
  809. if try_reboot:
  810. LOG.debug("Instance in transitional state (%(task_state)s) at "
  811. "start-up and power state is (%(power_state)s), "
  812. "triggering reboot",
  813. {'task_state': instance.task_state,
  814. 'power_state': current_power_state},
  815. instance=instance)
  816. # NOTE(mikal): if the instance was doing a soft reboot that got as
  817. # far as shutting down the instance but not as far as starting it
  818. # again, then we've just become a hard reboot. That means the
  819. # task state for the instance needs to change so that we're in one
  820. # of the expected task states for a hard reboot.
  821. if (instance.task_state in task_states.soft_reboot_states and
  822. reboot_type == 'HARD'):
  823. instance.task_state = task_states.REBOOT_PENDING_HARD
  824. instance.save()
  825. self.reboot_instance(context, instance, block_device_info=None,
  826. reboot_type=reboot_type)
  827. return
  828. elif (current_power_state == power_state.RUNNING and
  829. instance.task_state in [task_states.REBOOT_STARTED,
  830. task_states.REBOOT_STARTED_HARD,
  831. task_states.PAUSING,
  832. task_states.UNPAUSING]):
  833. LOG.warning("Instance in transitional state "
  834. "(%(task_state)s) at start-up and power state "
  835. "is (%(power_state)s), clearing task state",
  836. {'task_state': instance.task_state,
  837. 'power_state': current_power_state},
  838. instance=instance)
  839. instance.task_state = None
  840. instance.vm_state = vm_states.ACTIVE
  841. instance.save()
  842. elif (current_power_state == power_state.PAUSED and
  843. instance.task_state == task_states.UNPAUSING):
  844. LOG.warning("Instance in transitional state "
  845. "(%(task_state)s) at start-up and power state "
  846. "is (%(power_state)s), clearing task state "
  847. "and unpausing the instance",
  848. {'task_state': instance.task_state,
  849. 'power_state': current_power_state},
  850. instance=instance)
  851. try:
  852. self.unpause_instance(context, instance)
  853. except NotImplementedError:
  854. # Some virt driver didn't support pause and unpause
  855. pass
  856. except Exception:
  857. LOG.exception('Failed to unpause instance', instance=instance)
  858. return
  859. if instance.task_state == task_states.POWERING_OFF:
  860. try:
  861. LOG.debug("Instance in transitional state %s at start-up "
  862. "retrying stop request",
  863. instance.task_state, instance=instance)
  864. self.stop_instance(context, instance, True)
  865. except Exception:
  866. # we don't want that an exception blocks the init_host
  867. LOG.exception('Failed to stop instance', instance=instance)
  868. return
  869. if instance.task_state == task_states.POWERING_ON:
  870. try:
  871. LOG.debug("Instance in transitional state %s at start-up "
  872. "retrying start request",
  873. instance.task_state, instance=instance)
  874. self.start_instance(context, instance)
  875. except Exception:
  876. # we don't want that an exception blocks the init_host
  877. LOG.exception('Failed to start instance', instance=instance)
  878. return
  879. net_info = instance.get_network_info()
  880. try:
  881. self.driver.plug_vifs(instance, net_info)
  882. except NotImplementedError as e:
  883. LOG.debug(e, instance=instance)
  884. except exception.VirtualInterfacePlugException:
  885. # NOTE(mriedem): If we get here, it could be because the vif_type
  886. # in the cache is "binding_failed" or "unbound". The only way to
  887. # fix this is to try and bind the ports again, which would be
  888. # expensive here on host startup. We could add a check to
  889. # _heal_instance_info_cache to handle this, but probably only if
  890. # the instance task_state is None.
  891. LOG.exception('Virtual interface plugging failed for instance. '
  892. 'The port binding:host_id may need to be manually '
  893. 'updated.', instance=instance)
  894. self._set_instance_obj_error_state(context, instance)
  895. return
  896. if instance.task_state == task_states.RESIZE_MIGRATING:
  897. # We crashed during resize/migration, so roll back for safety
  898. try:
  899. # NOTE(mriedem): check old_vm_state for STOPPED here, if it's
  900. # not in system_metadata we default to True for backwards
  901. # compatibility
  902. power_on = (instance.system_metadata.get('old_vm_state') !=
  903. vm_states.STOPPED)
  904. block_dev_info = self._get_instance_block_device_info(context,
  905. instance)
  906. self.driver.finish_revert_migration(context,
  907. instance, net_info, block_dev_info, power_on)
  908. except Exception:
  909. LOG.exception('Failed to revert crashed migration',
  910. instance=instance)
  911. finally:
  912. LOG.info('Instance found in migrating state during '
  913. 'startup. Resetting task_state',
  914. instance=instance)
  915. instance.task_state = None
  916. instance.save()
  917. if instance.task_state == task_states.MIGRATING:
  918. # Live migration did not complete, but instance is on this
  919. # host, so reset the state.
  920. instance.task_state = None
  921. instance.save(expected_task_state=[task_states.MIGRATING])
  922. db_state = instance.power_state
  923. drv_state = self._get_power_state(context, instance)
  924. expect_running = (db_state == power_state.RUNNING and
  925. drv_state != db_state)
  926. LOG.debug('Current state is %(drv_state)s, state in DB is '
  927. '%(db_state)s.',
  928. {'drv_state': drv_state, 'db_state': db_state},
  929. instance=instance)
  930. if expect_running and CONF.resume_guests_state_on_host_boot:
  931. self._resume_guests_state(context, instance, net_info)
  932. elif drv_state == power_state.RUNNING:
  933. # VMwareAPI drivers will raise an exception
  934. try:
  935. self.driver.ensure_filtering_rules_for_instance(
  936. instance, net_info)
  937. except NotImplementedError:
  938. LOG.debug('Hypervisor driver does not support '
  939. 'firewall rules', instance=instance)
  940. def _resume_guests_state(self, context, instance, net_info):
  941. LOG.info('Rebooting instance after nova-compute restart.',
  942. instance=instance)
  943. block_device_info = \
  944. self._get_instance_block_device_info(context, instance)
  945. try:
  946. self.driver.resume_state_on_host_boot(
  947. context, instance, net_info, block_device_info)
  948. except NotImplementedError:
  949. LOG.warning('Hypervisor driver does not support '
  950. 'resume guests', instance=instance)
  951. except Exception:
  952. # NOTE(vish): The instance failed to resume, so we set the
  953. # instance to error and attempt to continue.
  954. LOG.warning('Failed to resume instance',
  955. instance=instance)
  956. self._set_instance_obj_error_state(context, instance)
  957. def _retry_reboot(self, context, instance, current_power_state):
  958. current_task_state = instance.task_state
  959. retry_reboot = False
  960. reboot_type = compute_utils.get_reboot_type(current_task_state,
  961. current_power_state)
  962. pending_soft = (current_task_state == task_states.REBOOT_PENDING and
  963. instance.vm_state in vm_states.ALLOW_SOFT_REBOOT)
  964. pending_hard = (current_task_state == task_states.REBOOT_PENDING_HARD
  965. and instance.vm_state in vm_states.ALLOW_HARD_REBOOT)
  966. started_not_running = (current_task_state in
  967. [task_states.REBOOT_STARTED,
  968. task_states.REBOOT_STARTED_HARD] and
  969. current_power_state != power_state.RUNNING)
  970. if pending_soft or pending_hard or started_not_running:
  971. retry_reboot = True
  972. return retry_reboot, reboot_type
  973. def handle_lifecycle_event(self, event):
  974. LOG.info("VM %(state)s (Lifecycle Event)",
  975. {'state': event.get_name()},
  976. instance_uuid=event.get_instance_uuid())
  977. context = nova.context.get_admin_context(read_deleted='yes')
  978. vm_power_state = None
  979. event_transition = event.get_transition()
  980. if event_transition == virtevent.EVENT_LIFECYCLE_STOPPED:
  981. vm_power_state = power_state.SHUTDOWN
  982. elif event_transition == virtevent.EVENT_LIFECYCLE_STARTED:
  983. vm_power_state = power_state.RUNNING
  984. elif event_transition in (
  985. virtevent.EVENT_LIFECYCLE_PAUSED,
  986. virtevent.EVENT_LIFECYCLE_POSTCOPY_STARTED,
  987. virtevent.EVENT_LIFECYCLE_MIGRATION_COMPLETED):
  988. vm_power_state = power_state.PAUSED
  989. elif event_transition == virtevent.EVENT_LIFECYCLE_RESUMED:
  990. vm_power_state = power_state.RUNNING
  991. elif event_transition == virtevent.EVENT_LIFECYCLE_SUSPENDED:
  992. vm_power_state = power_state.SUSPENDED
  993. else:
  994. LOG.warning("Unexpected lifecycle event: %d", event_transition)
  995. migrate_finish_statuses = {
  996. # This happens on the source node and indicates live migration
  997. # entered post-copy mode.
  998. virtevent.EVENT_LIFECYCLE_POSTCOPY_STARTED: 'running (post-copy)',
  999. # Suspended for offline migration.
  1000. virtevent.EVENT_LIFECYCLE_MIGRATION_COMPLETED: 'running'
  1001. }
  1002. expected_attrs = []
  1003. if event_transition in migrate_finish_statuses:
  1004. # Join on info_cache since that's needed in migrate_instance_start.
  1005. expected_attrs.append('info_cache')
  1006. instance = objects.Instance.get_by_uuid(context,
  1007. event.get_instance_uuid(),
  1008. expected_attrs=expected_attrs)
  1009. # Note(lpetrut): The event may be delayed, thus not reflecting
  1010. # the current instance power state. In that case, ignore the event.
  1011. current_power_state = self._get_power_state(context, instance)
  1012. if current_power_state == vm_power_state:
  1013. LOG.debug('Synchronizing instance power state after lifecycle '
  1014. 'event "%(event)s"; current vm_state: %(vm_state)s, '
  1015. 'current task_state: %(task_state)s, current DB '
  1016. 'power_state: %(db_power_state)s, VM power_state: '
  1017. '%(vm_power_state)s',
  1018. {'event': event.get_name(),
  1019. 'vm_state': instance.vm_state,
  1020. 'task_state': instance.task_state,
  1021. 'db_power_state': instance.power_state,
  1022. 'vm_power_state': vm_power_state},
  1023. instance_uuid=instance.uuid)
  1024. self._sync_instance_power_state(context,
  1025. instance,
  1026. vm_power_state)
  1027. # The following checks are for live migration. We want to activate
  1028. # the port binding for the destination host before the live migration
  1029. # is resumed on the destination host in order to reduce network
  1030. # downtime. Otherwise the ports are bound to the destination host
  1031. # in post_live_migration_at_destination.
  1032. # TODO(danms): Explore options for using a different live migration
  1033. # specific callback for this instead of piggy-backing on the
  1034. # handle_lifecycle_event callback.
  1035. if (instance.task_state == task_states.MIGRATING and
  1036. event_transition in migrate_finish_statuses):
  1037. status = migrate_finish_statuses[event_transition]
  1038. try:
  1039. migration = objects.Migration.get_by_instance_and_status(
  1040. context, instance.uuid, status)
  1041. LOG.debug('Binding ports to destination host: %s',
  1042. migration.dest_compute, instance=instance)
  1043. # For neutron, migrate_instance_start will activate the
  1044. # destination host port bindings, if there are any created by
  1045. # conductor before live migration started.
  1046. self.network_api.migrate_instance_start(
  1047. context, instance, migration)
  1048. except exception.MigrationNotFoundByStatus:
  1049. LOG.warning("Unable to find migration record with status "
  1050. "'%s' for instance. Port binding will happen in "
  1051. "post live migration.", status, instance=instance)
  1052. def handle_events(self, event):
  1053. if isinstance(event, virtevent.LifecycleEvent):
  1054. try:
  1055. self.handle_lifecycle_event(event)
  1056. except exception.InstanceNotFound:
  1057. LOG.debug("Event %s arrived for non-existent instance. The "
  1058. "instance was probably deleted.", event)
  1059. else:
  1060. LOG.debug("Ignoring event %s", event)
  1061. def init_virt_events(self):
  1062. if CONF.workarounds.handle_virt_lifecycle_events:
  1063. self.driver.register_event_listener(self.handle_events)
  1064. else:
  1065. # NOTE(mriedem): If the _sync_power_states periodic task is
  1066. # disabled we should emit a warning in the logs.
  1067. if CONF.sync_power_state_interval < 0:
  1068. LOG.warning('Instance lifecycle events from the compute '
  1069. 'driver have been disabled. Note that lifecycle '
  1070. 'changes to an instance outside of the compute '
  1071. 'service will not be synchronized '
  1072. 'automatically since the _sync_power_states '
  1073. 'periodic task is also disabled.')
  1074. else:
  1075. LOG.info('Instance lifecycle events from the compute '
  1076. 'driver have been disabled. Note that lifecycle '
  1077. 'changes to an instance outside of the compute '
  1078. 'service will only be synchronized by the '
  1079. '_sync_power_states periodic task.')
  1080. def init_host(self):
  1081. """Initialization for a standalone compute service."""
  1082. if CONF.pci.passthrough_whitelist:
  1083. # Simply loading the PCI passthrough whitelist will do a bunch of
  1084. # validation that would otherwise wait until the PciDevTracker is
  1085. # constructed when updating available resources for the compute
  1086. # node(s) in the resource tracker, effectively killing that task.
  1087. # So load up the whitelist when starting the compute service to
  1088. # flush any invalid configuration early so we can kill the service
  1089. # if the configuration is wrong.
  1090. whitelist.Whitelist(CONF.pci.passthrough_whitelist)
  1091. nova.conf.neutron.register_dynamic_opts(CONF)
  1092. self.driver.init_host(host=self.host)
  1093. context = nova.context.get_admin_context()
  1094. instances = objects.InstanceList.get_by_host(
  1095. context, self.host, expected_attrs=['info_cache', 'metadata'])
  1096. if CONF.defer_iptables_apply:
  1097. self.driver.filter_defer_apply_on()
  1098. self.init_virt_events()
  1099. try:
  1100. # checking that instance was not already evacuated to other host
  1101. evacuated_instances = self._destroy_evacuated_instances(context)
  1102. # Initialise instances on the host that are not evacuating
  1103. for instance in instances:
  1104. if instance.uuid not in evacuated_instances:
  1105. self._init_instance(context, instance)
  1106. # NOTE(gibi): collect all the instance uuids that is in some way
  1107. # was already handled above. Either by init_instance or by
  1108. # _destroy_evacuated_instances. This way we can limit the scope of
  1109. # the _error_out_instances_whose_build_was_interrupted call to look
  1110. # only for instances that have allocations on this node and not
  1111. # handled by the above calls.
  1112. already_handled = {instance.uuid for instance in instances}.union(
  1113. evacuated_instances)
  1114. # NOTE(gibi): If ironic and vcenter virt driver slow start time
  1115. # becomes problematic here then we should consider adding a config
  1116. # option or a driver flag to tell us if we should thread this out
  1117. # in the background on startup
  1118. self._error_out_instances_whose_build_was_interrupted(
  1119. context, already_handled)
  1120. finally:
  1121. if CONF.defer_iptables_apply:
  1122. self.driver.filter_defer_apply_off()
  1123. if instances:
  1124. # We only send the instance info to the scheduler on startup
  1125. # if there is anything to send, otherwise this host might
  1126. # not be mapped yet in a cell and the scheduler may have
  1127. # issues dealing with the information. Later changes to
  1128. # instances on this host will update the scheduler, or the
  1129. # _sync_scheduler_instance_info periodic task will.
  1130. self._update_scheduler_instance_info(context, instances)
  1131. def _error_out_instances_whose_build_was_interrupted(
  1132. self, context, already_handled_instances):
  1133. """If there are instances in BUILDING state that are not
  1134. assigned to this host but have allocations in placement towards
  1135. this compute that means the nova-compute service was
  1136. restarted while those instances waited for the resource claim
  1137. to finish and the _set_instance_host_and_node() to update the
  1138. instance.host field. We need to push them to ERROR state here to
  1139. prevent keeping them in BUILDING state forever.
  1140. :param context: The request context
  1141. :param already_handled_instances: The set of instance UUIDs that the
  1142. host initialization process already handled in some way.
  1143. """
  1144. # Strategy:
  1145. # 1) Get the allocations from placement for our compute node(s)
  1146. # 2) Remove the already handled instances from the consumer list;
  1147. # they are either already initialized or need to be skipped.
  1148. # 3) Check which remaining consumer is an instance in BUILDING state
  1149. # and push it to ERROR state.
  1150. LOG.info(
  1151. "Looking for unclaimed instances stuck in BUILDING status for "
  1152. "nodes managed by this host")
  1153. try:
  1154. node_names = self.driver.get_available_nodes()
  1155. except exception.VirtDriverNotReady:
  1156. LOG.warning(
  1157. "Virt driver is not ready. Therefore unable to error out any "
  1158. "instances stuck in BUILDING state on this node. If this is "
  1159. "the first time this service is starting on this host, then "
  1160. "you can ignore this warning.")
  1161. return
  1162. for node_name in node_names:
  1163. try:
  1164. cn_uuid = objects.ComputeNode.get_by_host_and_nodename(
  1165. context, self.host, node_name).uuid
  1166. except exception.ComputeHostNotFound:
  1167. LOG.warning(
  1168. "Compute node %s not found in the database and therefore "
  1169. "unable to error out any instances stuck in BUILDING "
  1170. "state on this node. If this is the first time this "
  1171. "service is starting on this host, then you can ignore "
  1172. "this warning.", node_name)
  1173. continue
  1174. f = self.reportclient.get_allocations_for_resource_provider
  1175. allocations = f(context, cn_uuid)
  1176. if allocations is None:
  1177. LOG.error(
  1178. "Could not retrieve compute node resource provider %s and "
  1179. "therefore unable to error out any instances stuck in "
  1180. "BUILDING state.", cn_uuid)
  1181. continue
  1182. not_handled_consumers = (set(allocations) -
  1183. already_handled_instances)
  1184. if not not_handled_consumers:
  1185. continue
  1186. filters = {
  1187. 'vm_state': vm_states.BUILDING,
  1188. 'uuid': not_handled_consumers
  1189. }
  1190. instances = objects.InstanceList.get_by_filters(
  1191. context, filters, expected_attrs=[])
  1192. for instance in instances:
  1193. LOG.debug(
  1194. "Instance spawn was interrupted before instance_claim, "
  1195. "setting instance to ERROR state", instance=instance)
  1196. self._set_instance_obj_error_state(
  1197. context, instance, clean_task_state=True)
  1198. def cleanup_host(self):
  1199. self.driver.register_event_listener(None)
  1200. self.instance_events.cancel_all_events()
  1201. self.driver.cleanup_host(host=self.host)
  1202. self._cleanup_live_migrations_in_pool()
  1203. def _cleanup_live_migrations_in_pool(self):
  1204. # Shutdown the pool so we don't get new requests.
  1205. self._live_migration_executor.shutdown(wait=False)
  1206. # For any queued migrations, cancel the migration and update
  1207. # its status.
  1208. for migration, future in self._waiting_live_migrations.values():
  1209. # If we got here before the Future was submitted then we need
  1210. # to move on since there isn't anything we can do.
  1211. if future is None:
  1212. continue
  1213. if future.cancel():
  1214. self._set_migration_status(migration, 'cancelled')
  1215. LOG.info('Successfully cancelled queued live migration.',
  1216. instance_uuid=migration.instance_uuid)
  1217. else:
  1218. LOG.warning('Unable to cancel live migration.',
  1219. instance_uuid=migration.instance_uuid)
  1220. self._waiting_live_migrations.clear()
  1221. def pre_start_hook(self):
  1222. """After the service is initialized, but before we fully bring
  1223. the service up by listening on RPC queues, make sure to update
  1224. our available resources (and indirectly our available nodes).
  1225. """
  1226. self.update_available_resource(nova.context.get_admin_context(),
  1227. startup=True)
  1228. def _get_power_state(self, context, instance):
  1229. """Retrieve the power state for the given instance."""
  1230. LOG.debug('Checking state', instance=instance)
  1231. try:
  1232. return self.driver.get_info(instance, use_cache=False).state
  1233. except exception.InstanceNotFound:
  1234. return power_state.NOSTATE
  1235. def get_console_topic(self, context):
  1236. """Retrieves the console host for a project on this host.
  1237. Currently this is just set in the flags for each compute host.
  1238. """
  1239. # TODO(mdragon): perhaps make this variable by console_type?
  1240. return '%s.%s' % (console_rpcapi.RPC_TOPIC, CONF.console_host)
  1241. @wrap_exception()
  1242. def get_console_pool_info(self, context, console_type):
  1243. return self.driver.get_console_pool_info(console_type)
  1244. @wrap_exception()
  1245. def refresh_instance_security_rules(self, context, instance):
  1246. """Tell the virtualization driver to refresh security rules for
  1247. an instance.
  1248. Passes straight through to the virtualization driver.
  1249. Synchronize the call because we may still be in the middle of
  1250. creating the instance.
  1251. """
  1252. @utils.synchronized(instance.uuid)
  1253. def _sync_refresh():
  1254. try:
  1255. return self.driver.refresh_instance_security_rules(instance)
  1256. except NotImplementedError:
  1257. LOG.debug('Hypervisor driver does not support '
  1258. 'security groups.', instance=instance)
  1259. return _sync_refresh()
  1260. def _await_block_device_map_created(self, context, vol_id):
  1261. # TODO(yamahata): creating volume simultaneously
  1262. # reduces creation time?
  1263. # TODO(yamahata): eliminate dumb polling
  1264. start = time.time()
  1265. retries = CONF.block_device_allocate_retries
  1266. if retries < 0:
  1267. LOG.warning("Treating negative config value (%(retries)s) for "
  1268. "'block_device_retries' as 0.",
  1269. {'retries': retries})
  1270. # (1) treat negative config value as 0
  1271. # (2) the configured value is 0, one attempt should be made
  1272. # (3) the configured value is > 0, then the total number attempts
  1273. # is (retries + 1)
  1274. attempts = 1
  1275. if retries >= 1:
  1276. attempts = retries + 1
  1277. for attempt in range(1, attempts + 1):
  1278. volume = self.volume_api.get(context, vol_id)
  1279. volume_status = volume['status']
  1280. if volume_status not in ['creating', 'downloading']:
  1281. if volume_status == 'available':
  1282. return attempt
  1283. LOG.warning("Volume id: %(vol_id)s finished being "
  1284. "created but its status is %(vol_status)s.",
  1285. {'vol_id': vol_id,
  1286. 'vol_status': volume_status})
  1287. break
  1288. greenthread.sleep(CONF.block_device_allocate_retries_interval)
  1289. raise exception.VolumeNotCreated(volume_id=vol_id,
  1290. seconds=int(time.time() - start),
  1291. attempts=attempt,
  1292. volume_status=volume_status)
  1293. def _decode_files(self, injected_files):
  1294. """Base64 decode the list of files to inject."""
  1295. if not injected_files:
  1296. return []
  1297. def _decode(f):
  1298. path, contents = f
  1299. # Py3 raises binascii.Error instead of TypeError as in Py27
  1300. try:
  1301. decoded = base64.b64decode(contents)
  1302. return path, decoded
  1303. except (TypeError, binascii.Error):
  1304. raise exception.Base64Exception(path=path)
  1305. return [_decode(f) for f in injected_files]
  1306. def _validate_instance_group_policy(self, context, instance,
  1307. scheduler_hints):
  1308. # NOTE(russellb) Instance group policy is enforced by the scheduler.
  1309. # However, there is a race condition with the enforcement of
  1310. # the policy. Since more than one instance may be scheduled at the
  1311. # same time, it's possible that more than one instance with an
  1312. # anti-affinity policy may end up here. It's also possible that
  1313. # multiple instances with an affinity policy could end up on different
  1314. # hosts. This is a validation step to make sure that starting the
  1315. # instance here doesn't violate the policy.
  1316. group_hint = scheduler_hints.get('group')
  1317. if not group_hint:
  1318. return
  1319. # The RequestSpec stores scheduler_hints as key=list pairs so we need
  1320. # to check the type on the value and pull the single entry out. The
  1321. # API request schema validates that the 'group' hint is a single value.
  1322. if isinstance(group_hint, list):
  1323. group_hint = group_hint[0]
  1324. @utils.synchronized(group_hint)
  1325. def _do_validation(context, instance, group_hint):
  1326. group = objects.InstanceGroup.get_by_hint(context, group_hint)
  1327. if group.policy and 'anti-affinity' == group.policy:
  1328. instances_uuids = objects.InstanceList.get_uuids_by_host(
  1329. context, self.host)
  1330. ins_on_host = set(instances_uuids)
  1331. members = set(group.members)
  1332. # Determine the set of instance group members on this host
  1333. # which are not the instance in question. This is used to
  1334. # determine how many other members from the same anti-affinity
  1335. # group can be on this host.
  1336. members_on_host = ins_on_host & members - set([instance.uuid])
  1337. rules = group.rules
  1338. if rules and 'max_server_per_host' in rules:
  1339. max_server = rules['max_server_per_host']
  1340. else:
  1341. max_server = 1
  1342. if len(members_on_host) >= max_server:
  1343. msg = _("Anti-affinity instance group policy "
  1344. "was violated.")
  1345. raise exception.RescheduledException(
  1346. instance_uuid=instance.uuid,
  1347. reason=msg)
  1348. elif group.policy and 'affinity' == group.policy:
  1349. group_hosts = group.get_hosts(exclude=[instance.uuid])
  1350. if group_hosts and self.host not in group_hosts:
  1351. msg = _("Affinity instance group policy was violated.")
  1352. raise exception.RescheduledException(
  1353. instance_uuid=instance.uuid,
  1354. reason=msg)
  1355. if not CONF.workarounds.disable_group_policy_check_upcall:
  1356. _do_validation(context, instance, group_hint)
  1357. def _log_original_error(self, exc_info, instance_uuid):
  1358. LOG.error('Error: %s', exc_info[1], instance_uuid=instance_uuid,
  1359. exc_info=exc_info)
  1360. def _reschedule(self, context, request_spec, filter_properties,
  1361. instance, reschedule_method, method_args, task_state,
  1362. exc_info=None, host_list=None):
  1363. """Attempt to re-schedule a compute operation."""
  1364. instance_uuid = instance.uuid
  1365. retry = filter_properties.get('retry')
  1366. if not retry:
  1367. # no retry information, do not reschedule.
  1368. LOG.debug("Retry info not present, will not reschedule",
  1369. instance_uuid=instance_uuid)
  1370. return
  1371. if not request_spec:
  1372. LOG.debug("No request spec, will not reschedule",
  1373. instance_uuid=instance_uuid)
  1374. return
  1375. LOG.debug("Re-scheduling %(method)s: attempt %(num)d",
  1376. {'method': reschedule_method.__name__,
  1377. 'num': retry['num_attempts']}, instance_uuid=instance_uuid)
  1378. # reset the task state:
  1379. self._instance_update(context, instance, task_state=task_state)
  1380. if exc_info:
  1381. # stringify to avoid circular ref problem in json serialization:
  1382. retry['exc'] = traceback.format_exception_only(exc_info[0],
  1383. exc_info[1])
  1384. reschedule_method(context, *method_args, host_list=host_list)
  1385. return True
  1386. @periodic_task.periodic_task
  1387. def _check_instance_build_time(self, context):
  1388. """Ensure that instances are not stuck in build."""
  1389. timeout = CONF.instance_build_timeout
  1390. if timeout == 0:
  1391. return
  1392. filters = {'vm_state': vm_states.BUILDING,
  1393. 'host': self.host}
  1394. building_insts = objects.InstanceList.get_by_filters(context,
  1395. filters, expected_attrs=[], use_slave=True)
  1396. for instance in building_insts:
  1397. if timeutils.is_older_than(instance.created_at, timeout):
  1398. self._set_instance_obj_error_state(context, instance)
  1399. LOG.warning("Instance build timed out. Set to error "
  1400. "state.", instance=instance)
  1401. def _check_instance_exists(self, context, instance):
  1402. """Ensure an instance with the same name is not already present."""
  1403. if self.driver.instance_exists(instance):
  1404. raise exception.InstanceExists(name=instance.name)
  1405. def _allocate_network_async(self, context, instance, requested_networks,
  1406. macs, security_groups, is_vpn):
  1407. """Method used to allocate networks in the background.
  1408. Broken out for testing.
  1409. """
  1410. # First check to see if we're specifically not supposed to allocate
  1411. # networks because if so, we can exit early.
  1412. if requested_networks and requested_networks.no_allocate:
  1413. LOG.debug("Not allocating networking since 'none' was specified.",
  1414. instance=instance)
  1415. return network_model.NetworkInfo([])
  1416. LOG.debug("Allocating IP information in the background.",
  1417. instance=instance)
  1418. retries = CONF.network_allocate_retries
  1419. attempts = retries + 1
  1420. retry_time = 1
  1421. bind_host_id = self.driver.network_binding_host_id(context, instance)
  1422. for attempt in range(1, attempts + 1):
  1423. try:
  1424. nwinfo = self.network_api.allocate_for_instance(
  1425. context, instance, vpn=is_vpn,
  1426. requested_networks=requested_networks,
  1427. macs=macs,
  1428. security_groups=security_groups,
  1429. bind_host_id=bind_host_id)
  1430. LOG.debug('Instance network_info: |%s|', nwinfo,
  1431. instance=instance)
  1432. instance.system_metadata['network_allocated'] = 'True'
  1433. # NOTE(JoshNang) do not save the instance here, as it can cause
  1434. # races. The caller shares a reference to instance and waits
  1435. # for this async greenthread to finish before calling
  1436. # instance.save().
  1437. return nwinfo
  1438. except Exception:
  1439. exc_info = sys.exc_info()
  1440. log_info = {'attempt': attempt,
  1441. 'attempts': attempts}
  1442. if attempt == attempts:
  1443. LOG.exception('Instance failed network setup '
  1444. 'after %(attempts)d attempt(s)',
  1445. log_info)
  1446. six.reraise(*exc_info)
  1447. LOG.warning('Instance failed network setup '
  1448. '(attempt %(attempt)d of %(attempts)d)',
  1449. log_info, instance=instance)
  1450. time.sleep(retry_time)
  1451. retry_time *= 2
  1452. if retry_time > 30:
  1453. retry_time = 30
  1454. # Not reached.
  1455. def _build_networks_for_instance(self, context, instance,
  1456. requested_networks, security_groups):
  1457. # If we're here from a reschedule the network may already be allocated.
  1458. if strutils.bool_from_string(
  1459. instance.system_metadata.get('network_allocated', 'False')):
  1460. # NOTE(alex_xu): The network_allocated is True means the network
  1461. # resource already allocated at previous scheduling, and the
  1462. # network setup is cleanup at previous. After rescheduling, the
  1463. # network resource need setup on the new host.
  1464. self.network_api.setup_instance_network_on_host(
  1465. context, instance, instance.host)
  1466. return self.network_api.get_instance_nw_info(context, instance)
  1467. if not self.is_neutron_security_groups:
  1468. security_groups = []
  1469. macs = self.driver.macs_for_instance(instance)
  1470. network_info = self._allocate_network(context, instance,
  1471. requested_networks, macs, security_groups)
  1472. return network_info
  1473. def _allocate_network(self, context, instance, requested_networks, macs,
  1474. security_groups):
  1475. """Start network allocation asynchronously. Return an instance
  1476. of NetworkInfoAsyncWrapper that can be used to retrieve the
  1477. allocated networks when the operation has finished.
  1478. """
  1479. # NOTE(comstud): Since we're allocating networks asynchronously,
  1480. # this task state has little meaning, as we won't be in this
  1481. # state for very long.
  1482. instance.vm_state = vm_states.BUILDING
  1483. instance.task_state = task_states.NETWORKING
  1484. instance.save(expected_task_state=[None])
  1485. is_vpn = False
  1486. return network_model.NetworkInfoAsyncWrapper(
  1487. self._allocate_network_async, context, instance,
  1488. requested_networks, macs, security_groups, is_vpn)
  1489. def _default_root_device_name(self, instance, image_meta, root_bdm):
  1490. try:
  1491. return self.driver.default_root_device_name(instance,
  1492. image_meta,
  1493. root_bdm)
  1494. except NotImplementedError:
  1495. return compute_utils.get_next_device_name(instance, [])
  1496. def _default_device_names_for_instance(self, instance,
  1497. root_device_name,
  1498. *block_device_lists):
  1499. try:
  1500. self.driver.default_device_names_for_instance(instance,
  1501. root_device_name,
  1502. *block_device_lists)
  1503. except NotImplementedError:
  1504. compute_utils.default_device_names_for_instance(
  1505. instance, root_device_name, *block_device_lists)
  1506. def _get_device_name_for_instance(self, instance, bdms, block_device_obj):
  1507. # NOTE(ndipanov): Copy obj to avoid changing the original
  1508. block_device_obj = block_device_obj.obj_clone()
  1509. try:
  1510. return self.driver.get_device_name_for_instance(
  1511. instance, bdms, block_device_obj)
  1512. except NotImplementedError:
  1513. return compute_utils.get_device_name_for_instance(
  1514. instance, bdms, block_device_obj.get("device_name"))
  1515. def _default_block_device_names(self, instance, image_meta, block_devices):
  1516. """Verify that all the devices have the device_name set. If not,
  1517. provide a default name.
  1518. It also ensures that there is a root_device_name and is set to the
  1519. first block device in the boot sequence (boot_index=0).
  1520. """
  1521. root_bdm = block_device.get_root_bdm(block_devices)
  1522. if not root_bdm:
  1523. return
  1524. # Get the root_device_name from the root BDM or the instance
  1525. root_device_name = None
  1526. update_root_bdm = False
  1527. if root_bdm.device_name:
  1528. root_device_name = root_bdm.device_name
  1529. instance.root_device_name = root_device_name
  1530. elif instance.root_device_name:
  1531. root_device_name = instance.root_device_name
  1532. root_bdm.device_name = root_device_name
  1533. update_root_bdm = True
  1534. else:
  1535. root_device_name = self._default_root_device_name(instance,
  1536. image_meta,
  1537. root_bdm)
  1538. instance.root_device_name = root_device_name
  1539. root_bdm.device_name = root_device_name
  1540. update_root_bdm = True
  1541. if update_root_bdm:
  1542. root_bdm.save()
  1543. ephemerals = list(filter(block_device.new_format_is_ephemeral,
  1544. block_devices))
  1545. swap = list(filter(block_device.new_format_is_swap,
  1546. block_devices))
  1547. block_device_mapping = list(filter(
  1548. driver_block_device.is_block_device_mapping, block_devices))
  1549. self._default_device_names_for_instance(instance,
  1550. root_device_name,
  1551. ephemerals,
  1552. swap,
  1553. block_device_mapping)
  1554. def _block_device_info_to_legacy(self, block_device_info):
  1555. """Convert BDI to the old format for drivers that need it."""
  1556. if self.use_legacy_block_device_info:
  1557. ephemerals = driver_block_device.legacy_block_devices(
  1558. driver.block_device_info_get_ephemerals(block_device_info))
  1559. mapping = driver_block_device.legacy_block_devices(
  1560. driver.block_device_info_get_mapping(block_device_info))
  1561. swap = block_device_info['swap']
  1562. if swap:
  1563. swap = swap.legacy()
  1564. block_device_info.update({
  1565. 'ephemerals': ephemerals,
  1566. 'swap': swap,
  1567. 'block_device_mapping': mapping})
  1568. def _add_missing_dev_names(self, bdms, instance):
  1569. for bdm in bdms:
  1570. if bdm.device_name is not None:
  1571. continue
  1572. device_name = self._get_device_name_for_instance(instance,
  1573. bdms, bdm)
  1574. values = {'device_name': device_name}
  1575. bdm.update(values)
  1576. bdm.save()
  1577. def _prep_block_device(self, context, instance, bdms):
  1578. """Set up the block device for an instance with error logging."""
  1579. try:
  1580. self._add_missing_dev_names(bdms, instance)
  1581. block_device_info = driver.get_block_device_info(instance, bdms)
  1582. mapping = driver.block_device_info_get_mapping(block_device_info)
  1583. driver_block_device.attach_block_devices(
  1584. mapping, context, instance, self.volume_api, self.driver,
  1585. wait_func=self._await_block_device_map_created)
  1586. self._block_device_info_to_legacy(block_device_info)
  1587. return block_device_info
  1588. except exception.OverQuota as e:
  1589. LOG.warning('Failed to create block device for instance due'
  1590. ' to exceeding volume related resource quota.'
  1591. ' Error: %s', e.message, instance=instance)
  1592. raise
  1593. except Exception as ex:
  1594. LOG.exception('Instance failed block device setup',
  1595. instance=instance)
  1596. # InvalidBDM will eventually result in a BuildAbortException when
  1597. # booting from volume, and will be recorded as an instance fault.
  1598. # Maintain the original exception message which most likely has
  1599. # useful details which the standard InvalidBDM error message lacks.
  1600. raise exception.InvalidBDM(six.text_type(ex))
  1601. def _update_instance_after_spawn(self, context, instance):
  1602. instance.power_state = self._get_power_state(context, instance)
  1603. instance.vm_state = vm_states.ACTIVE
  1604. instance.task_state = None
  1605. instance.launched_at = timeutils.utcnow()
  1606. configdrive.update_instance(instance)
  1607. def _update_scheduler_instance_info(self, context, instance):
  1608. """Sends an InstanceList with created or updated Instance objects to
  1609. the Scheduler client.
  1610. In the case of init_host, the value passed will already be an
  1611. InstanceList. Other calls will send individual Instance objects that
  1612. have been created or resized. In this case, we create an InstanceList
  1613. object containing that Instance.
  1614. """
  1615. if not self.send_instance_updates:
  1616. return
  1617. if isinstance(instance, obj_instance.Instance):
  1618. instance = objects.InstanceList(objects=[instance])
  1619. context = context.elevated()
  1620. self.scheduler_client.update_instance_info(context, self.host,
  1621. instance)
  1622. def _delete_scheduler_instance_info(self, context, instance_uuid):
  1623. """Sends the uuid of the deleted Instance to the Scheduler client."""
  1624. if not self.send_instance_updates:
  1625. return
  1626. context = context.elevated()
  1627. self.scheduler_client.delete_instance_info(context, self.host,
  1628. instance_uuid)
  1629. @periodic_task.periodic_task(spacing=CONF.scheduler_instance_sync_interval)
  1630. def _sync_scheduler_instance_info(self, context):
  1631. if not self.send_instance_updates:
  1632. return
  1633. context = context.elevated()
  1634. instances = objects.InstanceList.get_by_host(context, self.host,
  1635. expected_attrs=[],
  1636. use_slave=True)
  1637. uuids = [instance.uuid for instance in instances]
  1638. self.scheduler_client.sync_instance_info(context, self.host, uuids)
  1639. def _notify_about_instance_usage(self, context, instance, event_suffix,
  1640. network_info=None, extra_usage_info=None,
  1641. fault=None):
  1642. compute_utils.notify_about_instance_usage(
  1643. self.notifier, context, instance, event_suffix,
  1644. network_info=network_info,
  1645. extra_usage_info=extra_usage_info, fault=fault)
  1646. def _deallocate_network(self, context, instance,
  1647. requested_networks=None):
  1648. # If we were told not to allocate networks let's save ourselves
  1649. # the trouble of calling the network API.
  1650. if requested_networks and requested_networks.no_allocate:
  1651. LOG.debug("Skipping network deallocation for instance since "
  1652. "networking was not requested.", instance=instance)
  1653. return
  1654. LOG.debug('Deallocating network for instance', instance=instance)
  1655. with timeutils.StopWatch() as timer:
  1656. self.network_api.deallocate_for_instance(
  1657. context, instance, requested_networks=requested_networks)
  1658. # nova-network does an rpc call so we're OK tracking time spent here
  1659. LOG.info('Took %0.2f seconds to deallocate network for instance.',
  1660. timer.elapsed(), instance=instance)
  1661. def _get_instance_block_device_info(self, context, instance,
  1662. refresh_conn_info=False,
  1663. bdms=None):
  1664. """Transform block devices to the driver block_device format."""
  1665. if bdms is None:
  1666. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  1667. context, instance.uuid)
  1668. block_device_info = driver.get_block_device_info(instance, bdms)
  1669. if not refresh_conn_info:
  1670. # if the block_device_mapping has no value in connection_info
  1671. # (returned as None), don't include in the mapping
  1672. block_device_info['block_device_mapping'] = [
  1673. bdm for bdm in driver.block_device_info_get_mapping(
  1674. block_device_info)
  1675. if bdm.get('connection_info')]
  1676. else:
  1677. driver_block_device.refresh_conn_infos(
  1678. driver.block_device_info_get_mapping(block_device_info),
  1679. context, instance, self.volume_api, self.driver)
  1680. self._block_device_info_to_legacy(block_device_info)
  1681. return block_device_info
  1682. def _build_failed(self, node):
  1683. if CONF.compute.consecutive_build_service_disable_threshold:
  1684. rt = self._get_resource_tracker()
  1685. # NOTE(danms): Update our counter, but wait for the next
  1686. # update_available_resource() periodic to flush it to the DB
  1687. rt.build_failed(node)
  1688. def _build_succeeded(self, node):
  1689. rt = self._get_resource_tracker()
  1690. rt.build_succeeded(node)
  1691. @wrap_exception()
  1692. @reverts_task_state
  1693. @wrap_instance_fault
  1694. def build_and_run_instance(self, context, instance, image, request_spec,
  1695. filter_properties, admin_password=None,
  1696. injected_files=None, requested_networks=None,
  1697. security_groups=None, block_device_mapping=None,
  1698. node=None, limits=None, host_list=None):
  1699. @utils.synchronized(instance.uuid)
  1700. def _locked_do_build_and_run_instance(*args, **kwargs):
  1701. # NOTE(danms): We grab the semaphore with the instance uuid
  1702. # locked because we could wait in line to build this instance
  1703. # for a while and we want to make sure that nothing else tries
  1704. # to do anything with this instance while we wait.
  1705. with self._build_semaphore:
  1706. try:
  1707. result = self._do_build_and_run_instance(*args, **kwargs)
  1708. except Exception:
  1709. # NOTE(mriedem): This should really only happen if
  1710. # _decode_files in _do_build_and_run_instance fails, and
  1711. # that's before a guest is spawned so it's OK to remove
  1712. # allocations for the instance for this node from Placement
  1713. # below as there is no guest consuming resources anyway.
  1714. # The _decode_files case could be handled more specifically
  1715. # but that's left for another day.
  1716. result = build_results.FAILED
  1717. raise
  1718. finally:
  1719. if result == build_results.FAILED:
  1720. # Remove the allocation records from Placement for the
  1721. # instance if the build failed. The instance.host is
  1722. # likely set to None in _do_build_and_run_instance
  1723. # which means if the user deletes the instance, it
  1724. # will be deleted in the API, not the compute service.
  1725. # Setting the instance.host to None in
  1726. # _do_build_and_run_instance means that the
  1727. # ResourceTracker will no longer consider this instance
  1728. # to be claiming resources against it, so we want to
  1729. # reflect that same thing in Placement. No need to
  1730. # call this for a reschedule, as the allocations will
  1731. # have already been removed in
  1732. # self._do_build_and_run_instance().
  1733. self._delete_allocation_for_instance(context,
  1734. instance.uuid)
  1735. if result in (build_results.FAILED,
  1736. build_results.RESCHEDULED):
  1737. self._build_failed(node)
  1738. else:
  1739. self._build_succeeded(node)
  1740. # NOTE(danms): We spawn here to return the RPC worker thread back to
  1741. # the pool. Since what follows could take a really long time, we don't
  1742. # want to tie up RPC workers.
  1743. utils.spawn_n(_locked_do_build_and_run_instance,
  1744. context, instance, image, request_spec,
  1745. filter_properties, admin_password, injected_files,
  1746. requested_networks, security_groups,
  1747. block_device_mapping, node, limits, host_list)
  1748. def _delete_allocation_for_instance(self, context, instance_uuid):
  1749. rt = self._get_resource_tracker()
  1750. rt.reportclient.delete_allocation_for_instance(context, instance_uuid)
  1751. def _check_device_tagging(self, requested_networks, block_device_mapping):
  1752. tagging_requested = False
  1753. if requested_networks:
  1754. for net in requested_networks:
  1755. if 'tag' in net and net.tag is not None:
  1756. tagging_requested = True
  1757. break
  1758. if block_device_mapping and not tagging_requested:
  1759. for bdm in block_device_mapping:
  1760. if 'tag' in bdm and bdm.tag is not None:
  1761. tagging_requested = True
  1762. break
  1763. if (tagging_requested and
  1764. not self.driver.capabilities.get('supports_device_tagging',
  1765. False)):
  1766. raise exception.BuildAbortException('Attempt to boot guest with '
  1767. 'tagged devices on host that '
  1768. 'does not support tagging.')
  1769. def _check_trusted_certs(self, instance):
  1770. if (instance.trusted_certs and
  1771. not self.driver.capabilities.get('supports_trusted_certs',
  1772. False)):
  1773. raise exception.BuildAbortException(
  1774. 'Trusted image certificates provided on host that does not '
  1775. 'support certificate validation.')
  1776. @hooks.add_hook('build_instance')
  1777. @wrap_exception()
  1778. @reverts_task_state
  1779. @wrap_instance_event(prefix='compute')
  1780. @wrap_instance_fault
  1781. def _do_build_and_run_instance(self, context, instance, image,
  1782. request_spec, filter_properties, admin_password, injected_files,
  1783. requested_networks, security_groups, block_device_mapping,
  1784. node=None, limits=None, host_list=None):
  1785. try:
  1786. LOG.debug('Starting instance...', instance=instance)
  1787. instance.vm_state = vm_states.BUILDING
  1788. instance.task_state = None
  1789. instance.save(expected_task_state=
  1790. (task_states.SCHEDULING, None))
  1791. except exception.InstanceNotFound:
  1792. msg = 'Instance disappeared before build.'
  1793. LOG.debug(msg, instance=instance)
  1794. return build_results.FAILED
  1795. except exception.UnexpectedTaskStateError as e:
  1796. LOG.debug(e.format_message(), instance=instance)
  1797. return build_results.FAILED
  1798. # b64 decode the files to inject:
  1799. decoded_files = self._decode_files(injected_files)
  1800. if limits is None:
  1801. limits = {}
  1802. if node is None:
  1803. node = self._get_nodename(instance, refresh=True)
  1804. try:
  1805. with timeutils.StopWatch() as timer:
  1806. self._build_and_run_instance(context, instance, image,
  1807. decoded_files, admin_password, requested_networks,
  1808. security_groups, block_device_mapping, node, limits,
  1809. filter_properties, request_spec)
  1810. LOG.info('Took %0.2f seconds to build instance.',
  1811. timer.elapsed(), instance=instance)
  1812. return build_results.ACTIVE
  1813. except exception.RescheduledException as e:
  1814. retry = filter_properties.get('retry')
  1815. if not retry:
  1816. # no retry information, do not reschedule.
  1817. LOG.debug("Retry info not present, will not reschedule",
  1818. instance=instance)
  1819. self._cleanup_allocated_networks(context, instance,
  1820. requested_networks)
  1821. self._cleanup_volumes(context, instance,
  1822. block_device_mapping, raise_exc=False)
  1823. compute_utils.add_instance_fault_from_exc(context,
  1824. instance, e, sys.exc_info(),
  1825. fault_message=e.kwargs['reason'])
  1826. self._nil_out_instance_obj_host_and_node(instance)
  1827. self._set_instance_obj_error_state(context, instance,
  1828. clean_task_state=True)
  1829. return build_results.FAILED
  1830. LOG.debug(e.format_message(), instance=instance)
  1831. # This will be used for logging the exception
  1832. retry['exc'] = traceback.format_exception(*sys.exc_info())
  1833. # This will be used for setting the instance fault message
  1834. retry['exc_reason'] = e.kwargs['reason']
  1835. # NOTE(comstud): Deallocate networks if the driver wants
  1836. # us to do so.
  1837. # NOTE(mriedem): Always deallocate networking when using Neutron.
  1838. # This is to unbind any ports that the user supplied in the server
  1839. # create request, or delete any ports that nova created which were
  1840. # meant to be bound to this host. This check intentionally bypasses
  1841. # the result of deallocate_networks_on_reschedule because the
  1842. # default value in the driver is False, but that method was really
  1843. # only meant for Ironic and should be removed when nova-network is
  1844. # removed (since is_neutron() will then always be True).
  1845. # NOTE(vladikr): SR-IOV ports should be deallocated to
  1846. # allow new sriov pci devices to be allocated on a new host.
  1847. # Otherwise, if devices with pci addresses are already allocated
  1848. # on the destination host, the instance will fail to spawn.
  1849. # info_cache.network_info should be present at this stage.
  1850. if (self.driver.deallocate_networks_on_reschedule(instance) or
  1851. utils.is_neutron() or
  1852. self.deallocate_sriov_ports_on_reschedule(instance)):
  1853. self._cleanup_allocated_networks(context, instance,
  1854. requested_networks)
  1855. else:
  1856. # NOTE(alex_xu): Network already allocated and we don't
  1857. # want to deallocate them before rescheduling. But we need
  1858. # to cleanup those network resources setup on this host before
  1859. # rescheduling.
  1860. self.network_api.cleanup_instance_network_on_host(
  1861. context, instance, self.host)
  1862. self._nil_out_instance_obj_host_and_node(instance)
  1863. instance.task_state = task_states.SCHEDULING
  1864. instance.save()
  1865. # The instance will have already claimed resources from this host
  1866. # before this build was attempted. Now that it has failed, we need
  1867. # to unclaim those resources before casting to the conductor, so
  1868. # that if there are alternate hosts available for a retry, it can
  1869. # claim resources on that new host for the instance.
  1870. self._delete_allocation_for_instance(context, instance.uuid)
  1871. self.compute_task_api.build_instances(context, [instance],
  1872. image, filter_properties, admin_password,
  1873. injected_files, requested_networks, security_groups,
  1874. block_device_mapping, request_spec=request_spec,
  1875. host_lists=[host_list])
  1876. return build_results.RESCHEDULED
  1877. except (exception.InstanceNotFound,
  1878. exception.UnexpectedDeletingTaskStateError):
  1879. msg = 'Instance disappeared during build.'
  1880. LOG.debug(msg, instance=instance)
  1881. self._cleanup_allocated_networks(context, instance,
  1882. requested_networks)
  1883. return build_results.FAILED
  1884. except exception.BuildAbortException as e:
  1885. LOG.error(e.format_message(), instance=instance)
  1886. self._cleanup_allocated_networks(context, instance,
  1887. requested_networks)
  1888. self._cleanup_volumes(context, instance,
  1889. block_device_mapping, raise_exc=False)
  1890. compute_utils.add_instance_fault_from_exc(context, instance,
  1891. e, sys.exc_info())
  1892. self._nil_out_instance_obj_host_and_node(instance)
  1893. self._set_instance_obj_error_state(context, instance,
  1894. clean_task_state=True)
  1895. return build_results.FAILED
  1896. except Exception as e:
  1897. # Should not reach here.
  1898. LOG.exception('Unexpected build failure, not rescheduling build.',
  1899. instance=instance)
  1900. self._cleanup_allocated_networks(context, instance,
  1901. requested_networks)
  1902. self._cleanup_volumes(context, instance,
  1903. block_device_mapping, raise_exc=False)
  1904. compute_utils.add_instance_fault_from_exc(context, instance,
  1905. e, sys.exc_info())
  1906. self._nil_out_instance_obj_host_and_node(instance)
  1907. self._set_instance_obj_error_state(context, instance,
  1908. clean_task_state=True)
  1909. return build_results.FAILED
  1910. def deallocate_sriov_ports_on_reschedule(self, instance):
  1911. """Determine if networks are needed to be deallocated before reschedule
  1912. Check the cached network info for any assigned SR-IOV ports.
  1913. SR-IOV ports should be deallocated prior to rescheduling
  1914. in order to allow new sriov pci devices to be allocated on a new host.
  1915. """
  1916. info_cache = instance.info_cache
  1917. def _has_sriov_port(vif):
  1918. return vif['vnic_type'] in network_model.VNIC_TYPES_SRIOV
  1919. if (info_cache and info_cache.network_info):
  1920. for vif in info_cache.network_info:
  1921. if _has_sriov_port(vif):
  1922. return True
  1923. return False
  1924. @staticmethod
  1925. def _get_scheduler_hints(filter_properties, request_spec=None):
  1926. """Helper method to get scheduler hints.
  1927. This method prefers to get the hints out of the request spec, but that
  1928. might not be provided. Conductor will pass request_spec down to the
  1929. first compute chosen for a build but older computes will not pass
  1930. the request_spec to conductor's build_instances method for a
  1931. a reschedule, so if we're on a host via a retry, request_spec may not
  1932. be provided so we need to fallback to use the filter_properties
  1933. to get scheduler hints.
  1934. """
  1935. hints = {}
  1936. if request_spec is not None and 'scheduler_hints' in request_spec:
  1937. hints = request_spec.scheduler_hints
  1938. if not hints:
  1939. hints = filter_properties.get('scheduler_hints') or {}
  1940. return hints
  1941. def _build_and_run_instance(self, context, instance, image, injected_files,
  1942. admin_password, requested_networks, security_groups,
  1943. block_device_mapping, node, limits, filter_properties,
  1944. request_spec=None):
  1945. image_name = image.get('name')
  1946. self._notify_about_instance_usage(context, instance, 'create.start',
  1947. extra_usage_info={'image_name': image_name})
  1948. compute_utils.notify_about_instance_create(
  1949. context, instance, self.host,
  1950. phase=fields.NotificationPhase.START,
  1951. bdms=block_device_mapping)
  1952. # NOTE(mikal): cache the keystone roles associated with the instance
  1953. # at boot time for later reference
  1954. instance.system_metadata.update(
  1955. {'boot_roles': ','.join(context.roles)})
  1956. self._check_device_tagging(requested_networks, block_device_mapping)
  1957. self._check_trusted_certs(instance)
  1958. try:
  1959. scheduler_hints = self._get_scheduler_hints(filter_properties,
  1960. request_spec)
  1961. rt = self._get_resource_tracker()
  1962. with rt.instance_claim(context, instance, node, limits):
  1963. # NOTE(russellb) It's important that this validation be done
  1964. # *after* the resource tracker instance claim, as that is where
  1965. # the host is set on the instance.
  1966. self._validate_instance_group_policy(context, instance,
  1967. scheduler_hints)
  1968. image_meta = objects.ImageMeta.from_dict(image)
  1969. with self._build_resources(context, instance,
  1970. requested_networks, security_groups, image_meta,
  1971. block_device_mapping) as resources:
  1972. instance.vm_state = vm_states.BUILDING
  1973. instance.task_state = task_states.SPAWNING
  1974. # NOTE(JoshNang) This also saves the changes to the
  1975. # instance from _allocate_network_async, as they aren't
  1976. # saved in that function to prevent races.
  1977. instance.save(expected_task_state=
  1978. task_states.BLOCK_DEVICE_MAPPING)
  1979. block_device_info = resources['block_device_info']
  1980. network_info = resources['network_info']
  1981. allocs = resources['allocations']
  1982. LOG.debug('Start spawning the instance on the hypervisor.',
  1983. instance=instance)
  1984. with timeutils.StopWatch() as timer:
  1985. self.driver.spawn(context, instance, image_meta,
  1986. injected_files, admin_password,
  1987. allocs, network_info=network_info,
  1988. block_device_info=block_device_info)
  1989. LOG.info('Took %0.2f seconds to spawn the instance on '
  1990. 'the hypervisor.', timer.elapsed(),
  1991. instance=instance)
  1992. except (exception.InstanceNotFound,
  1993. exception.UnexpectedDeletingTaskStateError) as e:
  1994. with excutils.save_and_reraise_exception():
  1995. self._notify_about_instance_usage(context, instance,
  1996. 'create.error', fault=e)
  1997. tb = traceback.format_exc()
  1998. compute_utils.notify_about_instance_create(
  1999. context, instance, self.host,
  2000. phase=fields.NotificationPhase.ERROR, exception=e,
  2001. bdms=block_device_mapping, tb=tb)
  2002. except exception.ComputeResourcesUnavailable as e:
  2003. LOG.debug(e.format_message(), instance=instance)
  2004. self._notify_about_instance_usage(context, instance,
  2005. 'create.error', fault=e)
  2006. tb = traceback.format_exc()
  2007. compute_utils.notify_about_instance_create(
  2008. context, instance, self.host,
  2009. phase=fields.NotificationPhase.ERROR, exception=e,
  2010. bdms=block_device_mapping, tb=tb)
  2011. raise exception.RescheduledException(
  2012. instance_uuid=instance.uuid, reason=e.format_message())
  2013. except exception.BuildAbortException as e:
  2014. with excutils.save_and_reraise_exception():
  2015. LOG.debug(e.format_message(), instance=instance)
  2016. self._notify_about_instance_usage(context, instance,
  2017. 'create.error', fault=e)
  2018. tb = traceback.format_exc()
  2019. compute_utils.notify_about_instance_create(
  2020. context, instance, self.host,
  2021. phase=fields.NotificationPhase.ERROR, exception=e,
  2022. bdms=block_device_mapping, tb=tb)
  2023. except (exception.FixedIpLimitExceeded,
  2024. exception.NoMoreNetworks, exception.NoMoreFixedIps) as e:
  2025. LOG.warning('No more network or fixed IP to be allocated',
  2026. instance=instance)
  2027. self._notify_about_instance_usage(context, instance,
  2028. 'create.error', fault=e)
  2029. tb = traceback.format_exc()
  2030. compute_utils.notify_about_instance_create(
  2031. context, instance, self.host,
  2032. phase=fields.NotificationPhase.ERROR, exception=e,
  2033. bdms=block_device_mapping, tb=tb)
  2034. msg = _('Failed to allocate the network(s) with error %s, '
  2035. 'not rescheduling.') % e.format_message()
  2036. raise exception.BuildAbortException(instance_uuid=instance.uuid,
  2037. reason=msg)
  2038. except (exception.VirtualInterfaceCreateException,
  2039. exception.VirtualInterfaceMacAddressException,
  2040. exception.FixedIpInvalidOnHost,
  2041. exception.UnableToAutoAllocateNetwork) as e:
  2042. LOG.exception('Failed to allocate network(s)',
  2043. instance=instance)
  2044. self._notify_about_instance_usage(context, instance,
  2045. 'create.error', fault=e)
  2046. tb = traceback.format_exc()
  2047. compute_utils.notify_about_instance_create(
  2048. context, instance, self.host,
  2049. phase=fields.NotificationPhase.ERROR, exception=e,
  2050. bdms=block_device_mapping, tb=tb)
  2051. msg = _('Failed to allocate the network(s), not rescheduling.')
  2052. raise exception.BuildAbortException(instance_uuid=instance.uuid,
  2053. reason=msg)
  2054. except (exception.FlavorDiskTooSmall,
  2055. exception.FlavorMemoryTooSmall,
  2056. exception.ImageNotActive,
  2057. exception.ImageUnacceptable,
  2058. exception.InvalidDiskInfo,
  2059. exception.InvalidDiskFormat,
  2060. cursive_exception.SignatureVerificationError,
  2061. exception.CertificateValidationFailed,
  2062. exception.VolumeEncryptionNotSupported,
  2063. exception.InvalidInput,
  2064. # TODO(mriedem): We should be validating RequestedVRamTooHigh
  2065. # in the API during server create and rebuild.
  2066. exception.RequestedVRamTooHigh) as e:
  2067. self._notify_about_instance_usage(context, instance,
  2068. 'create.error', fault=e)
  2069. tb = traceback.format_exc()
  2070. compute_utils.notify_about_instance_create(
  2071. context, instance, self.host,
  2072. phase=fields.NotificationPhase.ERROR, exception=e,
  2073. bdms=block_device_mapping, tb=tb)
  2074. raise exception.BuildAbortException(instance_uuid=instance.uuid,
  2075. reason=e.format_message())
  2076. except Exception as e:
  2077. LOG.exception('Failed to build and run instance',
  2078. instance=instance)
  2079. self._notify_about_instance_usage(context, instance,
  2080. 'create.error', fault=e)
  2081. tb = traceback.format_exc()
  2082. compute_utils.notify_about_instance_create(
  2083. context, instance, self.host,
  2084. phase=fields.NotificationPhase.ERROR, exception=e,
  2085. bdms=block_device_mapping, tb=tb)
  2086. raise exception.RescheduledException(
  2087. instance_uuid=instance.uuid, reason=six.text_type(e))
  2088. # NOTE(alaski): This is only useful during reschedules, remove it now.
  2089. instance.system_metadata.pop('network_allocated', None)
  2090. # If CONF.default_access_ip_network_name is set, grab the
  2091. # corresponding network and set the access ip values accordingly.
  2092. network_name = CONF.default_access_ip_network_name
  2093. if (network_name and not instance.access_ip_v4 and
  2094. not instance.access_ip_v6):
  2095. # Note that when there are multiple ips to choose from, an
  2096. # arbitrary one will be chosen.
  2097. for vif in network_info:
  2098. if vif['network']['label'] == network_name:
  2099. for ip in vif.fixed_ips():
  2100. if not instance.access_ip_v4 and ip['version'] == 4:
  2101. instance.access_ip_v4 = ip['address']
  2102. if not instance.access_ip_v6 and ip['version'] == 6:
  2103. instance.access_ip_v6 = ip['address']
  2104. break
  2105. self._update_instance_after_spawn(context, instance)
  2106. try:
  2107. instance.save(expected_task_state=task_states.SPAWNING)
  2108. except (exception.InstanceNotFound,
  2109. exception.UnexpectedDeletingTaskStateError) as e:
  2110. with excutils.save_and_reraise_exception():
  2111. self._notify_about_instance_usage(context, instance,
  2112. 'create.error', fault=e)
  2113. tb = traceback.format_exc()
  2114. compute_utils.notify_about_instance_create(
  2115. context, instance, self.host,
  2116. phase=fields.NotificationPhase.ERROR, exception=e,
  2117. bdms=block_device_mapping, tb=tb)
  2118. self._update_scheduler_instance_info(context, instance)
  2119. self._notify_about_instance_usage(context, instance, 'create.end',
  2120. extra_usage_info={'message': _('Success')},
  2121. network_info=network_info)
  2122. compute_utils.notify_about_instance_create(context, instance,
  2123. self.host, phase=fields.NotificationPhase.END,
  2124. bdms=block_device_mapping)
  2125. @contextlib.contextmanager
  2126. def _build_resources(self, context, instance, requested_networks,
  2127. security_groups, image_meta, block_device_mapping):
  2128. resources = {}
  2129. network_info = None
  2130. try:
  2131. LOG.debug('Start building networks asynchronously for instance.',
  2132. instance=instance)
  2133. network_info = self._build_networks_for_instance(context, instance,
  2134. requested_networks, security_groups)
  2135. resources['network_info'] = network_info
  2136. except (exception.InstanceNotFound,
  2137. exception.UnexpectedDeletingTaskStateError):
  2138. raise
  2139. except exception.UnexpectedTaskStateError as e:
  2140. raise exception.BuildAbortException(instance_uuid=instance.uuid,
  2141. reason=e.format_message())
  2142. except Exception:
  2143. # Because this allocation is async any failures are likely to occur
  2144. # when the driver accesses network_info during spawn().
  2145. LOG.exception('Failed to allocate network(s)',
  2146. instance=instance)
  2147. msg = _('Failed to allocate the network(s), not rescheduling.')
  2148. raise exception.BuildAbortException(instance_uuid=instance.uuid,
  2149. reason=msg)
  2150. try:
  2151. # Perform any driver preparation work for the driver.
  2152. self.driver.prepare_for_spawn(instance)
  2153. # Depending on a virt driver, some network configuration is
  2154. # necessary before preparing block devices.
  2155. self.driver.prepare_networks_before_block_device_mapping(
  2156. instance, network_info)
  2157. # Verify that all the BDMs have a device_name set and assign a
  2158. # default to the ones missing it with the help of the driver.
  2159. self._default_block_device_names(instance, image_meta,
  2160. block_device_mapping)
  2161. LOG.debug('Start building block device mappings for instance.',
  2162. instance=instance)
  2163. instance.vm_state = vm_states.BUILDING
  2164. instance.task_state = task_states.BLOCK_DEVICE_MAPPING
  2165. instance.save()
  2166. block_device_info = self._prep_block_device(context, instance,
  2167. block_device_mapping)
  2168. resources['block_device_info'] = block_device_info
  2169. except (exception.InstanceNotFound,
  2170. exception.UnexpectedDeletingTaskStateError):
  2171. with excutils.save_and_reraise_exception():
  2172. # Make sure the async call finishes
  2173. if network_info is not None:
  2174. network_info.wait(do_raise=False)
  2175. self.driver.clean_networks_preparation(instance,
  2176. network_info)
  2177. self.driver.failed_spawn_cleanup(instance)
  2178. except (exception.UnexpectedTaskStateError,
  2179. exception.OverQuota, exception.InvalidBDM) as e:
  2180. # Make sure the async call finishes
  2181. if network_info is not None:
  2182. network_info.wait(do_raise=False)
  2183. self.driver.clean_networks_preparation(instance, network_info)
  2184. self.driver.failed_spawn_cleanup(instance)
  2185. raise exception.BuildAbortException(instance_uuid=instance.uuid,
  2186. reason=e.format_message())
  2187. except Exception:
  2188. LOG.exception('Failure prepping block device',
  2189. instance=instance)
  2190. # Make sure the async call finishes
  2191. if network_info is not None:
  2192. network_info.wait(do_raise=False)
  2193. self.driver.clean_networks_preparation(instance, network_info)
  2194. self.driver.failed_spawn_cleanup(instance)
  2195. msg = _('Failure prepping block device.')
  2196. raise exception.BuildAbortException(instance_uuid=instance.uuid,
  2197. reason=msg)
  2198. try:
  2199. resources['allocations'] = (
  2200. self.reportclient.get_allocations_for_consumer(context,
  2201. instance.uuid))
  2202. except Exception:
  2203. LOG.exception('Failure retrieving placement allocations',
  2204. instance=instance)
  2205. # Make sure the async call finishes
  2206. if network_info is not None:
  2207. network_info.wait(do_raise=False)
  2208. self.driver.failed_spawn_cleanup(instance)
  2209. msg = _('Failure retrieving placement allocations')
  2210. raise exception.BuildAbortException(instance_uuid=instance.uuid,
  2211. reason=msg)
  2212. try:
  2213. yield resources
  2214. except Exception as exc:
  2215. with excutils.save_and_reraise_exception() as ctxt:
  2216. if not isinstance(exc, (
  2217. exception.InstanceNotFound,
  2218. exception.UnexpectedDeletingTaskStateError)):
  2219. LOG.exception('Instance failed to spawn',
  2220. instance=instance)
  2221. # Make sure the async call finishes
  2222. if network_info is not None:
  2223. network_info.wait(do_raise=False)
  2224. # if network_info is empty we're likely here because of
  2225. # network allocation failure. Since nothing can be reused on
  2226. # rescheduling it's better to deallocate network to eliminate
  2227. # the chance of orphaned ports in neutron
  2228. deallocate_networks = False if network_info else True
  2229. try:
  2230. self._shutdown_instance(context, instance,
  2231. block_device_mapping, requested_networks,
  2232. try_deallocate_networks=deallocate_networks)
  2233. except Exception as exc2:
  2234. ctxt.reraise = False
  2235. LOG.warning('Could not clean up failed build,'
  2236. ' not rescheduling. Error: %s',
  2237. six.text_type(exc2))
  2238. raise exception.BuildAbortException(
  2239. instance_uuid=instance.uuid,
  2240. reason=six.text_type(exc))
  2241. def _cleanup_allocated_networks(self, context, instance,
  2242. requested_networks):
  2243. try:
  2244. self._deallocate_network(context, instance, requested_networks)
  2245. except Exception:
  2246. LOG.exception('Failed to deallocate networks', instance=instance)
  2247. return
  2248. instance.system_metadata['network_allocated'] = 'False'
  2249. try:
  2250. instance.save()
  2251. except exception.InstanceNotFound:
  2252. # NOTE(alaski): It's possible that we're cleaning up the networks
  2253. # because the instance was deleted. If that's the case then this
  2254. # exception will be raised by instance.save()
  2255. pass
  2256. def _try_deallocate_network(self, context, instance,
  2257. requested_networks=None):
  2258. # During auto-scale cleanup, we could be deleting a large number
  2259. # of servers at the same time and overloading parts of the system,
  2260. # so we retry a few times in case of connection failures to the
  2261. # networking service.
  2262. @loopingcall.RetryDecorator(
  2263. max_retry_count=3, inc_sleep_time=2, max_sleep_time=12,
  2264. exceptions=(keystone_exception.connection.ConnectFailure,))
  2265. def _deallocate_network_with_retries():
  2266. try:
  2267. self._deallocate_network(
  2268. context, instance, requested_networks)
  2269. except keystone_exception.connection.ConnectFailure as e:
  2270. # Provide a warning that something is amiss.
  2271. with excutils.save_and_reraise_exception():
  2272. LOG.warning('Failed to deallocate network for instance; '
  2273. 'retrying. Error: %s', six.text_type(e),
  2274. instance=instance)
  2275. try:
  2276. # tear down allocated network structure
  2277. _deallocate_network_with_retries()
  2278. except Exception as ex:
  2279. with excutils.save_and_reraise_exception():
  2280. LOG.error('Failed to deallocate network for instance. '
  2281. 'Error: %s', ex, instance=instance)
  2282. self._set_instance_obj_error_state(context, instance)
  2283. def _get_power_off_values(self, context, instance, clean_shutdown):
  2284. """Get the timing configuration for powering down this instance."""
  2285. if clean_shutdown:
  2286. timeout = compute_utils.get_value_from_system_metadata(instance,
  2287. key='image_os_shutdown_timeout', type=int,
  2288. default=CONF.shutdown_timeout)
  2289. retry_interval = CONF.compute.shutdown_retry_interval
  2290. else:
  2291. timeout = 0
  2292. retry_interval = 0
  2293. return timeout, retry_interval
  2294. def _power_off_instance(self, context, instance, clean_shutdown=True):
  2295. """Power off an instance on this host."""
  2296. timeout, retry_interval = self._get_power_off_values(context,
  2297. instance, clean_shutdown)
  2298. self.driver.power_off(instance, timeout, retry_interval)
  2299. def _shutdown_instance(self, context, instance,
  2300. bdms, requested_networks=None, notify=True,
  2301. try_deallocate_networks=True):
  2302. """Shutdown an instance on this host.
  2303. :param:context: security context
  2304. :param:instance: a nova.objects.Instance object
  2305. :param:bdms: the block devices for the instance to be torn
  2306. down
  2307. :param:requested_networks: the networks on which the instance
  2308. has ports
  2309. :param:notify: true if a final usage notification should be
  2310. emitted
  2311. :param:try_deallocate_networks: false if we should avoid
  2312. trying to teardown networking
  2313. """
  2314. context = context.elevated()
  2315. LOG.info('Terminating instance', instance=instance)
  2316. if notify:
  2317. self._notify_about_instance_usage(context, instance,
  2318. "shutdown.start")
  2319. compute_utils.notify_about_instance_action(context, instance,
  2320. self.host, action=fields.NotificationAction.SHUTDOWN,
  2321. phase=fields.NotificationPhase.START, bdms=bdms)
  2322. network_info = instance.get_network_info()
  2323. # NOTE(vish) get bdms before destroying the instance
  2324. vol_bdms = [bdm for bdm in bdms if bdm.is_volume]
  2325. block_device_info = self._get_instance_block_device_info(
  2326. context, instance, bdms=bdms)
  2327. # NOTE(melwitt): attempt driver destroy before releasing ip, may
  2328. # want to keep ip allocated for certain failures
  2329. try:
  2330. LOG.debug('Start destroying the instance on the hypervisor.',
  2331. instance=instance)
  2332. with timeutils.StopWatch() as timer:
  2333. self.driver.destroy(context, instance, network_info,
  2334. block_device_info)
  2335. LOG.info('Took %0.2f seconds to destroy the instance on the '
  2336. 'hypervisor.', timer.elapsed(), instance=instance)
  2337. except exception.InstancePowerOffFailure:
  2338. # if the instance can't power off, don't release the ip
  2339. with excutils.save_and_reraise_exception():
  2340. pass
  2341. except Exception:
  2342. with excutils.save_and_reraise_exception():
  2343. # deallocate ip and fail without proceeding to
  2344. # volume api calls, preserving current behavior
  2345. if try_deallocate_networks:
  2346. self._try_deallocate_network(context, instance,
  2347. requested_networks)
  2348. if try_deallocate_networks:
  2349. self._try_deallocate_network(context, instance, requested_networks)
  2350. timer.restart()
  2351. for bdm in vol_bdms:
  2352. try:
  2353. if bdm.attachment_id:
  2354. self.volume_api.attachment_delete(context,
  2355. bdm.attachment_id)
  2356. else:
  2357. # NOTE(vish): actual driver detach done in driver.destroy,
  2358. # so just tell cinder that we are done with it.
  2359. connector = self.driver.get_volume_connector(instance)
  2360. self.volume_api.terminate_connection(context,
  2361. bdm.volume_id,
  2362. connector)
  2363. self.volume_api.detach(context, bdm.volume_id,
  2364. instance.uuid)
  2365. except exception.VolumeAttachmentNotFound as exc:
  2366. LOG.debug('Ignoring VolumeAttachmentNotFound: %s', exc,
  2367. instance=instance)
  2368. except exception.DiskNotFound as exc:
  2369. LOG.debug('Ignoring DiskNotFound: %s', exc,
  2370. instance=instance)
  2371. except exception.VolumeNotFound as exc:
  2372. LOG.debug('Ignoring VolumeNotFound: %s', exc,
  2373. instance=instance)
  2374. except (cinder_exception.EndpointNotFound,
  2375. keystone_exception.EndpointNotFound) as exc:
  2376. LOG.warning('Ignoring EndpointNotFound for '
  2377. 'volume %(volume_id)s: %(exc)s',
  2378. {'exc': exc, 'volume_id': bdm.volume_id},
  2379. instance=instance)
  2380. except cinder_exception.ClientException as exc:
  2381. LOG.warning('Ignoring unknown cinder exception for '
  2382. 'volume %(volume_id)s: %(exc)s',
  2383. {'exc': exc, 'volume_id': bdm.volume_id},
  2384. instance=instance)
  2385. except Exception as exc:
  2386. LOG.warning('Ignoring unknown exception for '
  2387. 'volume %(volume_id)s: %(exc)s',
  2388. {'exc': exc, 'volume_id': bdm.volume_id},
  2389. instance=instance)
  2390. if vol_bdms:
  2391. LOG.info('Took %(time).2f seconds to detach %(num)s volumes '
  2392. 'for instance.',
  2393. {'time': timer.elapsed(), 'num': len(vol_bdms)},
  2394. instance=instance)
  2395. if notify:
  2396. self._notify_about_instance_usage(context, instance,
  2397. "shutdown.end")
  2398. compute_utils.notify_about_instance_action(context, instance,
  2399. self.host, action=fields.NotificationAction.SHUTDOWN,
  2400. phase=fields.NotificationPhase.END, bdms=bdms)
  2401. def _cleanup_volumes(self, context, instance, bdms, raise_exc=True,
  2402. detach=True):
  2403. exc_info = None
  2404. for bdm in bdms:
  2405. if detach and bdm.volume_id:
  2406. try:
  2407. LOG.debug("Detaching volume: %s", bdm.volume_id,
  2408. instance_uuid=instance.uuid)
  2409. destroy = bdm.delete_on_termination
  2410. self._detach_volume(context, bdm, instance,
  2411. destroy_bdm=destroy)
  2412. except Exception as exc:
  2413. exc_info = sys.exc_info()
  2414. LOG.warning('Failed to detach volume: %(volume_id)s '
  2415. 'due to %(exc)s',
  2416. {'volume_id': bdm.volume_id, 'exc': exc})
  2417. if bdm.volume_id and bdm.delete_on_termination:
  2418. try:
  2419. LOG.debug("Deleting volume: %s", bdm.volume_id,
  2420. instance_uuid=instance.uuid)
  2421. self.volume_api.delete(context, bdm.volume_id)
  2422. except Exception as exc:
  2423. exc_info = sys.exc_info()
  2424. LOG.warning('Failed to delete volume: %(volume_id)s '
  2425. 'due to %(exc)s',
  2426. {'volume_id': bdm.volume_id, 'exc': exc})
  2427. if exc_info is not None and raise_exc:
  2428. six.reraise(exc_info[0], exc_info[1], exc_info[2])
  2429. @hooks.add_hook("delete_instance")
  2430. def _delete_instance(self, context, instance, bdms):
  2431. """Delete an instance on this host.
  2432. :param context: nova request context
  2433. :param instance: nova.objects.instance.Instance object
  2434. :param bdms: nova.objects.block_device.BlockDeviceMappingList object
  2435. """
  2436. events = self.instance_events.clear_events_for_instance(instance)
  2437. if events:
  2438. LOG.debug('Events pending at deletion: %(events)s',
  2439. {'events': ','.join(events.keys())},
  2440. instance=instance)
  2441. self._notify_about_instance_usage(context, instance,
  2442. "delete.start")
  2443. compute_utils.notify_about_instance_action(context, instance,
  2444. self.host, action=fields.NotificationAction.DELETE,
  2445. phase=fields.NotificationPhase.START, bdms=bdms)
  2446. self._shutdown_instance(context, instance, bdms)
  2447. # NOTE(vish): We have already deleted the instance, so we have
  2448. # to ignore problems cleaning up the volumes. It
  2449. # would be nice to let the user know somehow that
  2450. # the volume deletion failed, but it is not
  2451. # acceptable to have an instance that can not be
  2452. # deleted. Perhaps this could be reworked in the
  2453. # future to set an instance fault the first time
  2454. # and to only ignore the failure if the instance
  2455. # is already in ERROR.
  2456. # NOTE(ameeda): The volumes already detached during the above
  2457. # _shutdown_instance() call and this is why
  2458. # detach is not requested from _cleanup_volumes()
  2459. # in this case
  2460. self._cleanup_volumes(context, instance, bdms,
  2461. raise_exc=False, detach=False)
  2462. # if a delete task succeeded, always update vm state and task
  2463. # state without expecting task state to be DELETING
  2464. instance.vm_state = vm_states.DELETED
  2465. instance.task_state = None
  2466. instance.power_state = power_state.NOSTATE
  2467. instance.terminated_at = timeutils.utcnow()
  2468. instance.save()
  2469. instance.destroy()
  2470. self._complete_deletion(context,
  2471. instance,
  2472. bdms)
  2473. @wrap_exception()
  2474. @reverts_task_state
  2475. @wrap_instance_event(prefix='compute')
  2476. @wrap_instance_fault
  2477. def terminate_instance(self, context, instance, bdms):
  2478. """Terminate an instance on this host."""
  2479. @utils.synchronized(instance.uuid)
  2480. def do_terminate_instance(instance, bdms):
  2481. # NOTE(mriedem): If we are deleting the instance while it was
  2482. # booting from volume, we could be racing with a database update of
  2483. # the BDM volume_id. Since the compute API passes the BDMs over RPC
  2484. # to compute here, the BDMs may be stale at this point. So check
  2485. # for any volume BDMs that don't have volume_id set and if we
  2486. # detect that, we need to refresh the BDM list before proceeding.
  2487. # TODO(mriedem): Move this into _delete_instance and make the bdms
  2488. # parameter optional.
  2489. for bdm in list(bdms):
  2490. if bdm.is_volume and not bdm.volume_id:
  2491. LOG.debug('There are potentially stale BDMs during '
  2492. 'delete, refreshing the BlockDeviceMappingList.',
  2493. instance=instance)
  2494. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  2495. context, instance.uuid)
  2496. break
  2497. try:
  2498. self._delete_instance(context, instance, bdms)
  2499. except exception.InstanceNotFound:
  2500. LOG.info("Instance disappeared during terminate",
  2501. instance=instance)
  2502. except Exception:
  2503. # As we're trying to delete always go to Error if something
  2504. # goes wrong that _delete_instance can't handle.
  2505. with excutils.save_and_reraise_exception():
  2506. LOG.exception('Setting instance vm_state to ERROR',
  2507. instance=instance)
  2508. self._set_instance_obj_error_state(context, instance)
  2509. do_terminate_instance(instance, bdms)
  2510. # NOTE(johannes): This is probably better named power_off_instance
  2511. # so it matches the driver method, but because of other issues, we
  2512. # can't use that name in grizzly.
  2513. @wrap_exception()
  2514. @reverts_task_state
  2515. @wrap_instance_event(prefix='compute')
  2516. @wrap_instance_fault
  2517. def stop_instance(self, context, instance, clean_shutdown):
  2518. """Stopping an instance on this host."""
  2519. @utils.synchronized(instance.uuid)
  2520. def do_stop_instance():
  2521. current_power_state = self._get_power_state(context, instance)
  2522. LOG.debug('Stopping instance; current vm_state: %(vm_state)s, '
  2523. 'current task_state: %(task_state)s, current DB '
  2524. 'power_state: %(db_power_state)s, current VM '
  2525. 'power_state: %(current_power_state)s',
  2526. {'vm_state': instance.vm_state,
  2527. 'task_state': instance.task_state,
  2528. 'db_power_state': instance.power_state,
  2529. 'current_power_state': current_power_state},
  2530. instance_uuid=instance.uuid)
  2531. # NOTE(mriedem): If the instance is already powered off, we are
  2532. # possibly tearing down and racing with other operations, so we can
  2533. # expect the task_state to be None if something else updates the
  2534. # instance and we're not locking it.
  2535. expected_task_state = [task_states.POWERING_OFF]
  2536. # The list of power states is from _sync_instance_power_state.
  2537. if current_power_state in (power_state.NOSTATE,
  2538. power_state.SHUTDOWN,
  2539. power_state.CRASHED):
  2540. LOG.info('Instance is already powered off in the '
  2541. 'hypervisor when stop is called.',
  2542. instance=instance)
  2543. expected_task_state.append(None)
  2544. self._notify_about_instance_usage(context, instance,
  2545. "power_off.start")
  2546. compute_utils.notify_about_instance_action(context, instance,
  2547. self.host, action=fields.NotificationAction.POWER_OFF,
  2548. phase=fields.NotificationPhase.START)
  2549. self._power_off_instance(context, instance, clean_shutdown)
  2550. instance.power_state = self._get_power_state(context, instance)
  2551. instance.vm_state = vm_states.STOPPED
  2552. instance.task_state = None
  2553. instance.save(expected_task_state=expected_task_state)
  2554. self._notify_about_instance_usage(context, instance,
  2555. "power_off.end")
  2556. compute_utils.notify_about_instance_action(context, instance,
  2557. self.host, action=fields.NotificationAction.POWER_OFF,
  2558. phase=fields.NotificationPhase.END)
  2559. do_stop_instance()
  2560. def _power_on(self, context, instance):
  2561. network_info = self.network_api.get_instance_nw_info(context, instance)
  2562. block_device_info = self._get_instance_block_device_info(context,
  2563. instance)
  2564. self.driver.power_on(context, instance,
  2565. network_info,
  2566. block_device_info)
  2567. def _delete_snapshot_of_shelved_instance(self, context, instance,
  2568. snapshot_id):
  2569. """Delete snapshot of shelved instance."""
  2570. try:
  2571. self.image_api.delete(context, snapshot_id)
  2572. except (exception.ImageNotFound,
  2573. exception.ImageNotAuthorized) as exc:
  2574. LOG.warning("Failed to delete snapshot "
  2575. "from shelved instance (%s).",
  2576. exc.format_message(), instance=instance)
  2577. except Exception:
  2578. LOG.exception("Something wrong happened when trying to "
  2579. "delete snapshot from shelved instance.",
  2580. instance=instance)
  2581. # NOTE(johannes): This is probably better named power_on_instance
  2582. # so it matches the driver method, but because of other issues, we
  2583. # can't use that name in grizzly.
  2584. @wrap_exception()
  2585. @reverts_task_state
  2586. @wrap_instance_event(prefix='compute')
  2587. @wrap_instance_fault
  2588. def start_instance(self, context, instance):
  2589. """Starting an instance on this host."""
  2590. self._notify_about_instance_usage(context, instance, "power_on.start")
  2591. compute_utils.notify_about_instance_action(context, instance,
  2592. self.host, action=fields.NotificationAction.POWER_ON,
  2593. phase=fields.NotificationPhase.START)
  2594. self._power_on(context, instance)
  2595. instance.power_state = self._get_power_state(context, instance)
  2596. instance.vm_state = vm_states.ACTIVE
  2597. instance.task_state = None
  2598. # Delete an image(VM snapshot) for a shelved instance
  2599. snapshot_id = instance.system_metadata.get('shelved_image_id')
  2600. if snapshot_id:
  2601. self._delete_snapshot_of_shelved_instance(context, instance,
  2602. snapshot_id)
  2603. # Delete system_metadata for a shelved instance
  2604. compute_utils.remove_shelved_keys_from_system_metadata(instance)
  2605. instance.save(expected_task_state=task_states.POWERING_ON)
  2606. self._notify_about_instance_usage(context, instance, "power_on.end")
  2607. compute_utils.notify_about_instance_action(context, instance,
  2608. self.host, action=fields.NotificationAction.POWER_ON,
  2609. phase=fields.NotificationPhase.END)
  2610. @messaging.expected_exceptions(NotImplementedError,
  2611. exception.TriggerCrashDumpNotSupported,
  2612. exception.InstanceNotRunning)
  2613. @wrap_exception()
  2614. @wrap_instance_event(prefix='compute')
  2615. @wrap_instance_fault
  2616. def trigger_crash_dump(self, context, instance):
  2617. """Trigger crash dump in an instance."""
  2618. self._notify_about_instance_usage(context, instance,
  2619. "trigger_crash_dump.start")
  2620. compute_utils.notify_about_instance_action(context, instance,
  2621. self.host, action=fields.NotificationAction.TRIGGER_CRASH_DUMP,
  2622. phase=fields.NotificationPhase.START)
  2623. # This method does not change task_state and power_state because the
  2624. # effect of a trigger depends on user's configuration.
  2625. self.driver.trigger_crash_dump(instance)
  2626. self._notify_about_instance_usage(context, instance,
  2627. "trigger_crash_dump.end")
  2628. compute_utils.notify_about_instance_action(context, instance,
  2629. self.host, action=fields.NotificationAction.TRIGGER_CRASH_DUMP,
  2630. phase=fields.NotificationPhase.END)
  2631. @wrap_exception()
  2632. @reverts_task_state
  2633. @wrap_instance_event(prefix='compute')
  2634. @wrap_instance_fault
  2635. def soft_delete_instance(self, context, instance):
  2636. """Soft delete an instance on this host."""
  2637. with compute_utils.notify_about_instance_delete(
  2638. self.notifier, context, instance, 'soft_delete'):
  2639. compute_utils.notify_about_instance_action(context, instance,
  2640. self.host, action=fields.NotificationAction.SOFT_DELETE,
  2641. phase=fields.NotificationPhase.START)
  2642. try:
  2643. self.driver.soft_delete(instance)
  2644. except NotImplementedError:
  2645. # Fallback to just powering off the instance if the
  2646. # hypervisor doesn't implement the soft_delete method
  2647. self.driver.power_off(instance)
  2648. instance.power_state = self._get_power_state(context, instance)
  2649. instance.vm_state = vm_states.SOFT_DELETED
  2650. instance.task_state = None
  2651. instance.save(expected_task_state=[task_states.SOFT_DELETING])
  2652. compute_utils.notify_about_instance_action(
  2653. context, instance, self.host,
  2654. action=fields.NotificationAction.SOFT_DELETE,
  2655. phase=fields.NotificationPhase.END)
  2656. @wrap_exception()
  2657. @reverts_task_state
  2658. @wrap_instance_event(prefix='compute')
  2659. @wrap_instance_fault
  2660. def restore_instance(self, context, instance):
  2661. """Restore a soft-deleted instance on this host."""
  2662. self._notify_about_instance_usage(context, instance, "restore.start")
  2663. compute_utils.notify_about_instance_action(context, instance,
  2664. self.host, action=fields.NotificationAction.RESTORE,
  2665. phase=fields.NotificationPhase.START)
  2666. try:
  2667. self.driver.restore(instance)
  2668. except NotImplementedError:
  2669. # Fallback to just powering on the instance if the hypervisor
  2670. # doesn't implement the restore method
  2671. self._power_on(context, instance)
  2672. instance.power_state = self._get_power_state(context, instance)
  2673. instance.vm_state = vm_states.ACTIVE
  2674. instance.task_state = None
  2675. instance.save(expected_task_state=task_states.RESTORING)
  2676. self._notify_about_instance_usage(context, instance, "restore.end")
  2677. compute_utils.notify_about_instance_action(context, instance,
  2678. self.host, action=fields.NotificationAction.RESTORE,
  2679. phase=fields.NotificationPhase.END)
  2680. @staticmethod
  2681. def _set_migration_status(migration, status):
  2682. """Set the status, and guard against a None being passed in.
  2683. This is useful as some of the compute RPC calls will not pass
  2684. a migration object in older versions. The check can be removed when
  2685. we move past 4.x major version of the RPC API.
  2686. """
  2687. if migration:
  2688. migration.status = status
  2689. migration.save()
  2690. def _rebuild_default_impl(self, context, instance, image_meta,
  2691. injected_files, admin_password, allocations,
  2692. bdms, detach_block_devices, attach_block_devices,
  2693. network_info=None,
  2694. evacuate=False, block_device_info=None,
  2695. preserve_ephemeral=False):
  2696. if preserve_ephemeral:
  2697. # The default code path does not support preserving ephemeral
  2698. # partitions.
  2699. raise exception.PreserveEphemeralNotSupported()
  2700. if evacuate:
  2701. detach_block_devices(context, bdms)
  2702. else:
  2703. self._power_off_instance(context, instance, clean_shutdown=True)
  2704. detach_block_devices(context, bdms)
  2705. self.driver.destroy(context, instance,
  2706. network_info=network_info,
  2707. block_device_info=block_device_info)
  2708. instance.task_state = task_states.REBUILD_BLOCK_DEVICE_MAPPING
  2709. instance.save(expected_task_state=[task_states.REBUILDING])
  2710. new_block_device_info = attach_block_devices(context, instance, bdms)
  2711. instance.task_state = task_states.REBUILD_SPAWNING
  2712. instance.save(
  2713. expected_task_state=[task_states.REBUILD_BLOCK_DEVICE_MAPPING])
  2714. with instance.mutated_migration_context():
  2715. self.driver.spawn(context, instance, image_meta, injected_files,
  2716. admin_password, allocations,
  2717. network_info=network_info,
  2718. block_device_info=new_block_device_info)
  2719. def _notify_instance_rebuild_error(self, context, instance, error, bdms):
  2720. tb = traceback.format_exc()
  2721. self._notify_about_instance_usage(context, instance,
  2722. 'rebuild.error', fault=error)
  2723. compute_utils.notify_about_instance_rebuild(
  2724. context, instance, self.host,
  2725. phase=fields.NotificationPhase.ERROR, exception=error, bdms=bdms,
  2726. tb=tb)
  2727. @messaging.expected_exceptions(exception.PreserveEphemeralNotSupported)
  2728. @wrap_exception()
  2729. @reverts_task_state
  2730. @wrap_instance_event(prefix='compute')
  2731. @wrap_instance_fault
  2732. def rebuild_instance(self, context, instance, orig_image_ref, image_ref,
  2733. injected_files, new_pass, orig_sys_metadata,
  2734. bdms, recreate, on_shared_storage,
  2735. preserve_ephemeral, migration,
  2736. scheduled_node, limits, request_spec):
  2737. """Destroy and re-make this instance.
  2738. A 'rebuild' effectively purges all existing data from the system and
  2739. remakes the VM with given 'metadata' and 'personalities'.
  2740. :param context: `nova.RequestContext` object
  2741. :param instance: Instance object
  2742. :param orig_image_ref: Original image_ref before rebuild
  2743. :param image_ref: New image_ref for rebuild
  2744. :param injected_files: Files to inject
  2745. :param new_pass: password to set on rebuilt instance
  2746. :param orig_sys_metadata: instance system metadata from pre-rebuild
  2747. :param bdms: block-device-mappings to use for rebuild
  2748. :param recreate: True if the instance is being recreated (e.g. the
  2749. hypervisor it was on failed) - cleanup of old state will be
  2750. skipped.
  2751. :param on_shared_storage: True if instance files on shared storage.
  2752. If not provided then information from the
  2753. driver will be used to decide if the instance
  2754. files are available or not on the target host
  2755. :param preserve_ephemeral: True if the default ephemeral storage
  2756. partition must be preserved on rebuild
  2757. :param migration: a Migration object if one was created for this
  2758. rebuild operation (if it's a part of evacuate)
  2759. :param scheduled_node: A node of the host chosen by the scheduler. If a
  2760. host was specified by the user, this will be
  2761. None
  2762. :param limits: Overcommit limits set by the scheduler. If a host was
  2763. specified by the user, this will be None
  2764. :param request_spec: a RequestSpec object used to schedule the instance
  2765. """
  2766. # recreate=True means the instance is being evacuated from a failed
  2767. # host to a new destination host (this host). The 'recreate' variable
  2768. # name is confusing, so rename it to evacuate here at the top, which
  2769. # is simpler than renaming a parameter in an RPC versioned method.
  2770. evacuate = recreate
  2771. context = context.elevated()
  2772. if evacuate:
  2773. LOG.info("Evacuating instance", instance=instance)
  2774. else:
  2775. LOG.info("Rebuilding instance", instance=instance)
  2776. rt = self._get_resource_tracker()
  2777. if evacuate:
  2778. # This is an evacuation to a new host, so we need to perform a
  2779. # resource claim.
  2780. rebuild_claim = rt.rebuild_claim
  2781. else:
  2782. # This is a rebuild to the same host, so we don't need to make
  2783. # a claim since the instance is already on this host.
  2784. rebuild_claim = claims.NopClaim
  2785. image_meta = {}
  2786. if image_ref:
  2787. image_meta = self.image_api.get(context, image_ref)
  2788. elif evacuate:
  2789. # For evacuate the API does not send down the image_ref since the
  2790. # image does not change so just get it from what was stashed in
  2791. # the instance system_metadata when the instance was created (or
  2792. # last rebuilt). This also works for volume-backed instances.
  2793. image_meta = instance.image_meta
  2794. # NOTE(mriedem): On an evacuate, we need to update
  2795. # the instance's host and node properties to reflect it's
  2796. # destination node for the evacuate.
  2797. if not scheduled_node:
  2798. if evacuate:
  2799. try:
  2800. compute_node = self._get_compute_info(context, self.host)
  2801. scheduled_node = compute_node.hypervisor_hostname
  2802. except exception.ComputeHostNotFound:
  2803. LOG.exception('Failed to get compute_info for %s',
  2804. self.host)
  2805. else:
  2806. scheduled_node = instance.node
  2807. with self._error_out_instance_on_exception(context, instance):
  2808. try:
  2809. claim_ctxt = rebuild_claim(
  2810. context, instance, scheduled_node,
  2811. limits=limits, image_meta=image_meta,
  2812. migration=migration)
  2813. self._do_rebuild_instance_with_claim(
  2814. claim_ctxt, context, instance, orig_image_ref,
  2815. image_ref, injected_files, new_pass, orig_sys_metadata,
  2816. bdms, evacuate, on_shared_storage, preserve_ephemeral,
  2817. migration, request_spec)
  2818. except (exception.ComputeResourcesUnavailable,
  2819. exception.RescheduledException) as e:
  2820. if isinstance(e, exception.ComputeResourcesUnavailable):
  2821. LOG.debug("Could not rebuild instance on this host, not "
  2822. "enough resources available.", instance=instance)
  2823. else:
  2824. # RescheduledException is raised by the late server group
  2825. # policy check during evacuation if a parallel scheduling
  2826. # violated the policy.
  2827. # We catch the RescheduledException here but we don't have
  2828. # the plumbing to do an actual reschedule so we abort the
  2829. # operation.
  2830. LOG.debug("Could not rebuild instance on this host, "
  2831. "late server group check failed.",
  2832. instance=instance)
  2833. # NOTE(ndipanov): We just abort the build for now and leave a
  2834. # migration record for potential cleanup later
  2835. self._set_migration_status(migration, 'failed')
  2836. # Since the claim failed, we need to remove the allocation
  2837. # created against the destination node. Note that we can only
  2838. # get here when evacuating to a destination node. Rebuilding
  2839. # on the same host (not evacuate) uses the NopClaim which will
  2840. # not raise ComputeResourcesUnavailable.
  2841. rt.delete_allocation_for_evacuated_instance(
  2842. context, instance, scheduled_node, node_type='destination')
  2843. self._notify_instance_rebuild_error(context, instance, e, bdms)
  2844. raise exception.BuildAbortException(
  2845. instance_uuid=instance.uuid, reason=e.format_message())
  2846. except (exception.InstanceNotFound,
  2847. exception.UnexpectedDeletingTaskStateError) as e:
  2848. LOG.debug('Instance was deleted while rebuilding',
  2849. instance=instance)
  2850. self._set_migration_status(migration, 'failed')
  2851. self._notify_instance_rebuild_error(context, instance, e, bdms)
  2852. except Exception as e:
  2853. self._set_migration_status(migration, 'failed')
  2854. if evacuate or scheduled_node is not None:
  2855. rt.delete_allocation_for_evacuated_instance(
  2856. context, instance, scheduled_node,
  2857. node_type='destination')
  2858. self._notify_instance_rebuild_error(context, instance, e, bdms)
  2859. raise
  2860. else:
  2861. instance.apply_migration_context()
  2862. # NOTE (ndipanov): This save will now update the host and node
  2863. # attributes making sure that next RT pass is consistent since
  2864. # it will be based on the instance and not the migration DB
  2865. # entry.
  2866. instance.host = self.host
  2867. instance.node = scheduled_node
  2868. instance.save()
  2869. instance.drop_migration_context()
  2870. # NOTE (ndipanov): Mark the migration as done only after we
  2871. # mark the instance as belonging to this host.
  2872. self._set_migration_status(migration, 'done')
  2873. def _do_rebuild_instance_with_claim(self, claim_context, *args, **kwargs):
  2874. """Helper to avoid deep nesting in the top-level method."""
  2875. with claim_context:
  2876. self._do_rebuild_instance(*args, **kwargs)
  2877. @staticmethod
  2878. def _get_image_name(image_meta):
  2879. if image_meta.obj_attr_is_set("name"):
  2880. return image_meta.name
  2881. else:
  2882. return ''
  2883. def _do_rebuild_instance(self, context, instance, orig_image_ref,
  2884. image_ref, injected_files, new_pass,
  2885. orig_sys_metadata, bdms, evacuate,
  2886. on_shared_storage, preserve_ephemeral,
  2887. migration, request_spec):
  2888. orig_vm_state = instance.vm_state
  2889. if evacuate:
  2890. if request_spec:
  2891. # NOTE(gibi): Do a late check of server group policy as
  2892. # parallel scheduling could violate such policy. This will
  2893. # cause the evacuate to fail as rebuild does not implement
  2894. # reschedule.
  2895. hints = self._get_scheduler_hints({}, request_spec)
  2896. self._validate_instance_group_policy(context, instance, hints)
  2897. if not self.driver.capabilities.get("supports_evacuate", False):
  2898. raise exception.InstanceEvacuateNotSupported
  2899. self._check_instance_exists(context, instance)
  2900. if on_shared_storage is None:
  2901. LOG.debug('on_shared_storage is not provided, using driver '
  2902. 'information to decide if the instance needs to '
  2903. 'be evacuated')
  2904. on_shared_storage = self.driver.instance_on_disk(instance)
  2905. elif (on_shared_storage !=
  2906. self.driver.instance_on_disk(instance)):
  2907. # To cover case when admin expects that instance files are
  2908. # on shared storage, but not accessible and vice versa
  2909. raise exception.InvalidSharedStorage(
  2910. _("Invalid state of instance files on shared"
  2911. " storage"))
  2912. if on_shared_storage:
  2913. LOG.info('disk on shared storage, evacuating using'
  2914. ' existing disk')
  2915. else:
  2916. image_ref = orig_image_ref = instance.image_ref
  2917. LOG.info("disk not on shared storage, evacuating from:"
  2918. " '%s'", str(image_ref))
  2919. if image_ref:
  2920. image_meta = objects.ImageMeta.from_image_ref(
  2921. context, self.image_api, image_ref)
  2922. else:
  2923. image_meta = instance.image_meta
  2924. # We check trusted certs capabilities for both evacuate (rebuild on
  2925. # another host) and rebuild (rebuild on the same host) because for
  2926. # evacuate we need to make sure an instance with trusted certs can
  2927. # have the image verified with those certs during rebuild, and for
  2928. # rebuild we could be rebuilding a server that started out with no
  2929. # trusted certs on this host, and then was rebuilt with trusted certs
  2930. # for a new image, in which case we need to validate that new image
  2931. # with the trusted certs during the rebuild.
  2932. self._check_trusted_certs(instance)
  2933. # This instance.exists message should contain the original
  2934. # image_ref, not the new one. Since the DB has been updated
  2935. # to point to the new one... we have to override it.
  2936. orig_image_ref_url = self.image_api.generate_image_url(orig_image_ref,
  2937. context)
  2938. extra_usage_info = {'image_ref_url': orig_image_ref_url}
  2939. compute_utils.notify_usage_exists(
  2940. self.notifier, context, instance, self.host,
  2941. current_period=True, system_metadata=orig_sys_metadata,
  2942. extra_usage_info=extra_usage_info)
  2943. # This message should contain the new image_ref
  2944. extra_usage_info = {'image_name': self._get_image_name(image_meta)}
  2945. self._notify_about_instance_usage(context, instance,
  2946. "rebuild.start", extra_usage_info=extra_usage_info)
  2947. # NOTE: image_name is not included in the versioned notification
  2948. # because we already provide the image_uuid in the notification
  2949. # payload and the image details can be looked up via the uuid.
  2950. compute_utils.notify_about_instance_rebuild(
  2951. context, instance, self.host,
  2952. phase=fields.NotificationPhase.START,
  2953. bdms=bdms)
  2954. instance.power_state = self._get_power_state(context, instance)
  2955. instance.task_state = task_states.REBUILDING
  2956. instance.save(expected_task_state=[task_states.REBUILDING])
  2957. if evacuate:
  2958. self.network_api.setup_networks_on_host(
  2959. context, instance, self.host)
  2960. # For nova-network this is needed to move floating IPs
  2961. # For neutron this updates the host in the port binding
  2962. # TODO(cfriesen): this network_api call and the one above
  2963. # are so similar, we should really try to unify them.
  2964. self.network_api.setup_instance_network_on_host(
  2965. context, instance, self.host, migration)
  2966. # TODO(mriedem): Consider decorating setup_instance_network_on_host
  2967. # with @base_api.refresh_cache and then we wouldn't need this
  2968. # explicit call to get_instance_nw_info.
  2969. network_info = self.network_api.get_instance_nw_info(context,
  2970. instance)
  2971. else:
  2972. network_info = instance.get_network_info()
  2973. allocations = self.reportclient.get_allocations_for_consumer(
  2974. context, instance.uuid)
  2975. if bdms is None:
  2976. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  2977. context, instance.uuid)
  2978. block_device_info = \
  2979. self._get_instance_block_device_info(
  2980. context, instance, bdms=bdms)
  2981. def detach_block_devices(context, bdms):
  2982. for bdm in bdms:
  2983. if bdm.is_volume:
  2984. # NOTE (ildikov): Having the attachment_id set in the BDM
  2985. # means that it's the new Cinder attach/detach flow
  2986. # (available from v3.44). In that case we explicitly
  2987. # attach and detach the volumes through attachment level
  2988. # operations. In this scenario _detach_volume will delete
  2989. # the existing attachment which would make the volume
  2990. # status change to 'available' if we don't pre-create
  2991. # another empty attachment before deleting the old one.
  2992. attachment_id = None
  2993. if bdm.attachment_id:
  2994. attachment_id = self.volume_api.attachment_create(
  2995. context, bdm['volume_id'], instance.uuid)['id']
  2996. self._detach_volume(context, bdm, instance,
  2997. destroy_bdm=False)
  2998. if attachment_id:
  2999. bdm.attachment_id = attachment_id
  3000. bdm.save()
  3001. files = self._decode_files(injected_files)
  3002. kwargs = dict(
  3003. context=context,
  3004. instance=instance,
  3005. image_meta=image_meta,
  3006. injected_files=files,
  3007. admin_password=new_pass,
  3008. allocations=allocations,
  3009. bdms=bdms,
  3010. detach_block_devices=detach_block_devices,
  3011. attach_block_devices=self._prep_block_device,
  3012. block_device_info=block_device_info,
  3013. network_info=network_info,
  3014. preserve_ephemeral=preserve_ephemeral,
  3015. evacuate=evacuate)
  3016. try:
  3017. with instance.mutated_migration_context():
  3018. self.driver.rebuild(**kwargs)
  3019. except NotImplementedError:
  3020. # NOTE(rpodolyaka): driver doesn't provide specialized version
  3021. # of rebuild, fall back to the default implementation
  3022. self._rebuild_default_impl(**kwargs)
  3023. self._update_instance_after_spawn(context, instance)
  3024. instance.save(expected_task_state=[task_states.REBUILD_SPAWNING])
  3025. if orig_vm_state == vm_states.STOPPED:
  3026. LOG.info("bringing vm to original state: '%s'",
  3027. orig_vm_state, instance=instance)
  3028. instance.vm_state = vm_states.ACTIVE
  3029. instance.task_state = task_states.POWERING_OFF
  3030. instance.progress = 0
  3031. instance.save()
  3032. self.stop_instance(context, instance, False)
  3033. # TODO(melwitt): We should clean up instance console tokens here in the
  3034. # case of evacuate. The instance is on a new host and will need to
  3035. # establish a new console connection.
  3036. self._update_scheduler_instance_info(context, instance)
  3037. self._notify_about_instance_usage(
  3038. context, instance, "rebuild.end",
  3039. network_info=network_info,
  3040. extra_usage_info=extra_usage_info)
  3041. compute_utils.notify_about_instance_rebuild(
  3042. context, instance, self.host,
  3043. phase=fields.NotificationPhase.END,
  3044. bdms=bdms)
  3045. def _handle_bad_volumes_detached(self, context, instance, bad_devices,
  3046. block_device_info):
  3047. """Handle cases where the virt-layer had to detach non-working volumes
  3048. in order to complete an operation.
  3049. """
  3050. for bdm in block_device_info['block_device_mapping']:
  3051. if bdm.get('mount_device') in bad_devices:
  3052. try:
  3053. volume_id = bdm['connection_info']['data']['volume_id']
  3054. except KeyError:
  3055. continue
  3056. # NOTE(sirp): ideally we'd just call
  3057. # `compute_api.detach_volume` here but since that hits the
  3058. # DB directly, that's off limits from within the
  3059. # compute-manager.
  3060. #
  3061. # API-detach
  3062. LOG.info("Detaching from volume api: %s", volume_id)
  3063. self.volume_api.begin_detaching(context, volume_id)
  3064. # Manager-detach
  3065. self.detach_volume(context, volume_id, instance)
  3066. @wrap_exception()
  3067. @reverts_task_state
  3068. @wrap_instance_event(prefix='compute')
  3069. @wrap_instance_fault
  3070. def reboot_instance(self, context, instance, block_device_info,
  3071. reboot_type):
  3072. @utils.synchronized(instance.uuid)
  3073. def do_reboot_instance(context, instance, block_device_info,
  3074. reboot_type):
  3075. self._reboot_instance(context, instance, block_device_info,
  3076. reboot_type)
  3077. do_reboot_instance(context, instance, block_device_info, reboot_type)
  3078. def _reboot_instance(self, context, instance, block_device_info,
  3079. reboot_type):
  3080. """Reboot an instance on this host."""
  3081. # acknowledge the request made it to the manager
  3082. if reboot_type == "SOFT":
  3083. instance.task_state = task_states.REBOOT_PENDING
  3084. expected_states = task_states.soft_reboot_states
  3085. else:
  3086. instance.task_state = task_states.REBOOT_PENDING_HARD
  3087. expected_states = task_states.hard_reboot_states
  3088. context = context.elevated()
  3089. LOG.info("Rebooting instance", instance=instance)
  3090. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  3091. context, instance.uuid)
  3092. block_device_info = self._get_instance_block_device_info(
  3093. context, instance, bdms=bdms)
  3094. network_info = self.network_api.get_instance_nw_info(context, instance)
  3095. self._notify_about_instance_usage(context, instance, "reboot.start")
  3096. compute_utils.notify_about_instance_action(
  3097. context, instance, self.host,
  3098. action=fields.NotificationAction.REBOOT,
  3099. phase=fields.NotificationPhase.START,
  3100. bdms=bdms
  3101. )
  3102. instance.power_state = self._get_power_state(context, instance)
  3103. instance.save(expected_task_state=expected_states)
  3104. if instance.power_state != power_state.RUNNING:
  3105. state = instance.power_state
  3106. running = power_state.RUNNING
  3107. LOG.warning('trying to reboot a non-running instance:'
  3108. ' (state: %(state)s expected: %(running)s)',
  3109. {'state': state, 'running': running},
  3110. instance=instance)
  3111. def bad_volumes_callback(bad_devices):
  3112. self._handle_bad_volumes_detached(
  3113. context, instance, bad_devices, block_device_info)
  3114. try:
  3115. # Don't change it out of rescue mode
  3116. if instance.vm_state == vm_states.RESCUED:
  3117. new_vm_state = vm_states.RESCUED
  3118. else:
  3119. new_vm_state = vm_states.ACTIVE
  3120. new_power_state = None
  3121. if reboot_type == "SOFT":
  3122. instance.task_state = task_states.REBOOT_STARTED
  3123. expected_state = task_states.REBOOT_PENDING
  3124. else:
  3125. instance.task_state = task_states.REBOOT_STARTED_HARD
  3126. expected_state = task_states.REBOOT_PENDING_HARD
  3127. instance.save(expected_task_state=expected_state)
  3128. self.driver.reboot(context, instance,
  3129. network_info,
  3130. reboot_type,
  3131. block_device_info=block_device_info,
  3132. bad_volumes_callback=bad_volumes_callback)
  3133. except Exception as error:
  3134. with excutils.save_and_reraise_exception() as ctxt:
  3135. exc_info = sys.exc_info()
  3136. # if the reboot failed but the VM is running don't
  3137. # put it into an error state
  3138. new_power_state = self._get_power_state(context, instance)
  3139. if new_power_state == power_state.RUNNING:
  3140. LOG.warning('Reboot failed but instance is running',
  3141. instance=instance)
  3142. compute_utils.add_instance_fault_from_exc(context,
  3143. instance, error, exc_info)
  3144. self._notify_about_instance_usage(context, instance,
  3145. 'reboot.error', fault=error)
  3146. tb = traceback.format_exc()
  3147. compute_utils.notify_about_instance_action(
  3148. context, instance, self.host,
  3149. action=fields.NotificationAction.REBOOT,
  3150. phase=fields.NotificationPhase.ERROR,
  3151. exception=error, bdms=bdms, tb=tb
  3152. )
  3153. ctxt.reraise = False
  3154. else:
  3155. LOG.error('Cannot reboot instance: %s', error,
  3156. instance=instance)
  3157. self._set_instance_obj_error_state(context, instance)
  3158. if not new_power_state:
  3159. new_power_state = self._get_power_state(context, instance)
  3160. try:
  3161. instance.power_state = new_power_state
  3162. instance.vm_state = new_vm_state
  3163. instance.task_state = None
  3164. instance.save()
  3165. except exception.InstanceNotFound:
  3166. LOG.warning("Instance disappeared during reboot",
  3167. instance=instance)
  3168. self._notify_about_instance_usage(context, instance, "reboot.end")
  3169. compute_utils.notify_about_instance_action(
  3170. context, instance, self.host,
  3171. action=fields.NotificationAction.REBOOT,
  3172. phase=fields.NotificationPhase.END,
  3173. bdms=bdms
  3174. )
  3175. @delete_image_on_error
  3176. def _do_snapshot_instance(self, context, image_id, instance):
  3177. self._snapshot_instance(context, image_id, instance,
  3178. task_states.IMAGE_BACKUP)
  3179. @wrap_exception()
  3180. @reverts_task_state
  3181. @wrap_instance_event(prefix='compute')
  3182. @wrap_instance_fault
  3183. def backup_instance(self, context, image_id, instance, backup_type,
  3184. rotation):
  3185. """Backup an instance on this host.
  3186. :param backup_type: daily | weekly
  3187. :param rotation: int representing how many backups to keep around
  3188. """
  3189. self._do_snapshot_instance(context, image_id, instance)
  3190. self._rotate_backups(context, instance, backup_type, rotation)
  3191. @wrap_exception()
  3192. @reverts_task_state
  3193. @wrap_instance_event(prefix='compute')
  3194. @wrap_instance_fault
  3195. @delete_image_on_error
  3196. def snapshot_instance(self, context, image_id, instance):
  3197. """Snapshot an instance on this host.
  3198. :param context: security context
  3199. :param image_id: glance.db.sqlalchemy.models.Image.Id
  3200. :param instance: a nova.objects.instance.Instance object
  3201. """
  3202. # NOTE(dave-mcnally) the task state will already be set by the api
  3203. # but if the compute manager has crashed/been restarted prior to the
  3204. # request getting here the task state may have been cleared so we set
  3205. # it again and things continue normally
  3206. try:
  3207. instance.task_state = task_states.IMAGE_SNAPSHOT
  3208. instance.save(
  3209. expected_task_state=task_states.IMAGE_SNAPSHOT_PENDING)
  3210. except exception.InstanceNotFound:
  3211. # possibility instance no longer exists, no point in continuing
  3212. LOG.debug("Instance not found, could not set state %s "
  3213. "for instance.",
  3214. task_states.IMAGE_SNAPSHOT, instance=instance)
  3215. return
  3216. except exception.UnexpectedDeletingTaskStateError:
  3217. LOG.debug("Instance being deleted, snapshot cannot continue",
  3218. instance=instance)
  3219. return
  3220. self._snapshot_instance(context, image_id, instance,
  3221. task_states.IMAGE_SNAPSHOT)
  3222. def _snapshot_instance(self, context, image_id, instance,
  3223. expected_task_state):
  3224. context = context.elevated()
  3225. instance.power_state = self._get_power_state(context, instance)
  3226. try:
  3227. instance.save()
  3228. LOG.info('instance snapshotting', instance=instance)
  3229. if instance.power_state != power_state.RUNNING:
  3230. state = instance.power_state
  3231. running = power_state.RUNNING
  3232. LOG.warning('trying to snapshot a non-running instance: '
  3233. '(state: %(state)s expected: %(running)s)',
  3234. {'state': state, 'running': running},
  3235. instance=instance)
  3236. self._notify_about_instance_usage(
  3237. context, instance, "snapshot.start")
  3238. compute_utils.notify_about_instance_snapshot(context, instance,
  3239. self.host, phase=fields.NotificationPhase.START,
  3240. snapshot_image_id=image_id)
  3241. def update_task_state(task_state,
  3242. expected_state=expected_task_state):
  3243. instance.task_state = task_state
  3244. instance.save(expected_task_state=expected_state)
  3245. with timeutils.StopWatch() as timer:
  3246. self.driver.snapshot(context, instance, image_id,
  3247. update_task_state)
  3248. LOG.info('Took %0.2f seconds to snapshot the instance on '
  3249. 'the hypervisor.', timer.elapsed(), instance=instance)
  3250. instance.task_state = None
  3251. instance.save(expected_task_state=task_states.IMAGE_UPLOADING)
  3252. self._notify_about_instance_usage(context, instance,
  3253. "snapshot.end")
  3254. compute_utils.notify_about_instance_snapshot(context, instance,
  3255. self.host, phase=fields.NotificationPhase.END,
  3256. snapshot_image_id=image_id)
  3257. except (exception.InstanceNotFound,
  3258. exception.UnexpectedDeletingTaskStateError):
  3259. # the instance got deleted during the snapshot
  3260. # Quickly bail out of here
  3261. msg = 'Instance disappeared during snapshot'
  3262. LOG.debug(msg, instance=instance)
  3263. try:
  3264. image = self.image_api.get(context, image_id)
  3265. if image['status'] != 'active':
  3266. self.image_api.delete(context, image_id)
  3267. except exception.ImageNotFound:
  3268. LOG.debug('Image not found during clean up %s', image_id)
  3269. except Exception:
  3270. LOG.warning("Error while trying to clean up image %s",
  3271. image_id, instance=instance)
  3272. except exception.ImageNotFound:
  3273. instance.task_state = None
  3274. instance.save()
  3275. LOG.warning("Image not found during snapshot", instance=instance)
  3276. def _post_interrupted_snapshot_cleanup(self, context, instance):
  3277. self.driver.post_interrupted_snapshot_cleanup(context, instance)
  3278. @messaging.expected_exceptions(NotImplementedError)
  3279. @wrap_exception()
  3280. def volume_snapshot_create(self, context, instance, volume_id,
  3281. create_info):
  3282. self.driver.volume_snapshot_create(context, instance, volume_id,
  3283. create_info)
  3284. @messaging.expected_exceptions(NotImplementedError)
  3285. @wrap_exception()
  3286. def volume_snapshot_delete(self, context, instance, volume_id,
  3287. snapshot_id, delete_info):
  3288. self.driver.volume_snapshot_delete(context, instance, volume_id,
  3289. snapshot_id, delete_info)
  3290. @wrap_instance_fault
  3291. def _rotate_backups(self, context, instance, backup_type, rotation):
  3292. """Delete excess backups associated to an instance.
  3293. Instances are allowed a fixed number of backups (the rotation number);
  3294. this method deletes the oldest backups that exceed the rotation
  3295. threshold.
  3296. :param context: security context
  3297. :param instance: Instance dict
  3298. :param backup_type: a user-defined type, like "daily" or "weekly" etc.
  3299. :param rotation: int representing how many backups to keep around;
  3300. None if rotation shouldn't be used (as in the case of snapshots)
  3301. """
  3302. filters = {'property-image_type': 'backup',
  3303. 'property-backup_type': backup_type,
  3304. 'property-instance_uuid': instance.uuid}
  3305. images = self.image_api.get_all(context, filters=filters,
  3306. sort_key='created_at', sort_dir='desc')
  3307. num_images = len(images)
  3308. LOG.debug("Found %(num_images)d images (rotation: %(rotation)d)",
  3309. {'num_images': num_images, 'rotation': rotation},
  3310. instance=instance)
  3311. if num_images > rotation:
  3312. # NOTE(sirp): this deletes all backups that exceed the rotation
  3313. # limit
  3314. excess = len(images) - rotation
  3315. LOG.debug("Rotating out %d backups", excess,
  3316. instance=instance)
  3317. for i in range(excess):
  3318. image = images.pop()
  3319. image_id = image['id']
  3320. LOG.debug("Deleting image %s", image_id,
  3321. instance=instance)
  3322. try:
  3323. self.image_api.delete(context, image_id)
  3324. except exception.ImageNotFound:
  3325. LOG.info("Failed to find image %(image_id)s to "
  3326. "delete", {'image_id': image_id},
  3327. instance=instance)
  3328. except (exception.ImageDeleteConflict, Exception) as exc:
  3329. LOG.info("Failed to delete image %(image_id)s during "
  3330. "deleting excess backups. "
  3331. "Continuing for next image.. %(exc)s",
  3332. {'image_id': image_id, 'exc': exc},
  3333. instance=instance)
  3334. @wrap_exception()
  3335. @reverts_task_state
  3336. @wrap_instance_event(prefix='compute')
  3337. @wrap_instance_fault
  3338. def set_admin_password(self, context, instance, new_pass):
  3339. """Set the root/admin password for an instance on this host.
  3340. This is generally only called by API password resets after an
  3341. image has been built.
  3342. @param context: Nova auth context.
  3343. @param instance: Nova instance object.
  3344. @param new_pass: The admin password for the instance.
  3345. """
  3346. context = context.elevated()
  3347. if new_pass is None:
  3348. # Generate a random password
  3349. new_pass = utils.generate_password()
  3350. current_power_state = self._get_power_state(context, instance)
  3351. expected_state = power_state.RUNNING
  3352. if current_power_state != expected_state:
  3353. instance.task_state = None
  3354. instance.save(expected_task_state=task_states.UPDATING_PASSWORD)
  3355. _msg = _('instance %s is not running') % instance.uuid
  3356. raise exception.InstancePasswordSetFailed(
  3357. instance=instance.uuid, reason=_msg)
  3358. try:
  3359. self.driver.set_admin_password(instance, new_pass)
  3360. LOG.info("Admin password set", instance=instance)
  3361. instance.task_state = None
  3362. instance.save(
  3363. expected_task_state=task_states.UPDATING_PASSWORD)
  3364. except exception.InstanceAgentNotEnabled:
  3365. with excutils.save_and_reraise_exception():
  3366. LOG.debug('Guest agent is not enabled for the instance.',
  3367. instance=instance)
  3368. instance.task_state = None
  3369. instance.save(
  3370. expected_task_state=task_states.UPDATING_PASSWORD)
  3371. except exception.SetAdminPasswdNotSupported:
  3372. with excutils.save_and_reraise_exception():
  3373. LOG.info('set_admin_password is not supported '
  3374. 'by this driver or guest instance.',
  3375. instance=instance)
  3376. instance.task_state = None
  3377. instance.save(
  3378. expected_task_state=task_states.UPDATING_PASSWORD)
  3379. except NotImplementedError:
  3380. LOG.warning('set_admin_password is not implemented '
  3381. 'by this driver or guest instance.',
  3382. instance=instance)
  3383. instance.task_state = None
  3384. instance.save(
  3385. expected_task_state=task_states.UPDATING_PASSWORD)
  3386. raise NotImplementedError(_('set_admin_password is not '
  3387. 'implemented by this driver or guest '
  3388. 'instance.'))
  3389. except exception.UnexpectedTaskStateError:
  3390. # interrupted by another (most likely delete) task
  3391. # do not retry
  3392. raise
  3393. except Exception:
  3394. # Catch all here because this could be anything.
  3395. LOG.exception('set_admin_password failed', instance=instance)
  3396. # We create a new exception here so that we won't
  3397. # potentially reveal password information to the
  3398. # API caller. The real exception is logged above
  3399. _msg = _('error setting admin password')
  3400. raise exception.InstancePasswordSetFailed(
  3401. instance=instance.uuid, reason=_msg)
  3402. @wrap_exception()
  3403. @reverts_task_state
  3404. @wrap_instance_fault
  3405. def inject_file(self, context, path, file_contents, instance):
  3406. """Write a file to the specified path in an instance on this host."""
  3407. # NOTE(russellb) Remove this method, as well as the underlying virt
  3408. # driver methods, when the compute rpc interface is bumped to 4.x
  3409. # as it is no longer used.
  3410. context = context.elevated()
  3411. current_power_state = self._get_power_state(context, instance)
  3412. expected_state = power_state.RUNNING
  3413. if current_power_state != expected_state:
  3414. LOG.warning('trying to inject a file into a non-running '
  3415. '(state: %(current_state)s expected: '
  3416. '%(expected_state)s)',
  3417. {'current_state': current_power_state,
  3418. 'expected_state': expected_state},
  3419. instance=instance)
  3420. LOG.info('injecting file to %s', path, instance=instance)
  3421. self.driver.inject_file(instance, path, file_contents)
  3422. def _get_rescue_image(self, context, instance, rescue_image_ref=None):
  3423. """Determine what image should be used to boot the rescue VM."""
  3424. # 1. If rescue_image_ref is passed in, use that for rescue.
  3425. # 2. Else, use the base image associated with instance's current image.
  3426. # The idea here is to provide the customer with a rescue
  3427. # environment which they are familiar with.
  3428. # So, if they built their instance off of a Debian image,
  3429. # their rescue VM will also be Debian.
  3430. # 3. As a last resort, use instance's current image.
  3431. if not rescue_image_ref:
  3432. system_meta = utils.instance_sys_meta(instance)
  3433. rescue_image_ref = system_meta.get('image_base_image_ref')
  3434. if not rescue_image_ref:
  3435. LOG.warning('Unable to find a different image to use for '
  3436. 'rescue VM, using instance\'s current image',
  3437. instance=instance)
  3438. rescue_image_ref = instance.image_ref
  3439. return objects.ImageMeta.from_image_ref(
  3440. context, self.image_api, rescue_image_ref)
  3441. @wrap_exception()
  3442. @reverts_task_state
  3443. @wrap_instance_event(prefix='compute')
  3444. @wrap_instance_fault
  3445. def rescue_instance(self, context, instance, rescue_password,
  3446. rescue_image_ref, clean_shutdown):
  3447. context = context.elevated()
  3448. LOG.info('Rescuing', instance=instance)
  3449. admin_password = (rescue_password if rescue_password else
  3450. utils.generate_password())
  3451. network_info = self.network_api.get_instance_nw_info(context, instance)
  3452. rescue_image_meta = self._get_rescue_image(context, instance,
  3453. rescue_image_ref)
  3454. extra_usage_info = {'rescue_image_name':
  3455. self._get_image_name(rescue_image_meta)}
  3456. self._notify_about_instance_usage(context, instance,
  3457. "rescue.start", extra_usage_info=extra_usage_info,
  3458. network_info=network_info)
  3459. compute_utils.notify_about_instance_rescue_action(
  3460. context, instance, self.host, rescue_image_ref,
  3461. phase=fields.NotificationPhase.START)
  3462. try:
  3463. self._power_off_instance(context, instance, clean_shutdown)
  3464. self.driver.rescue(context, instance,
  3465. network_info,
  3466. rescue_image_meta, admin_password)
  3467. except Exception as e:
  3468. LOG.exception("Error trying to Rescue Instance",
  3469. instance=instance)
  3470. self._set_instance_obj_error_state(context, instance)
  3471. raise exception.InstanceNotRescuable(
  3472. instance_id=instance.uuid,
  3473. reason=_("Driver Error: %s") % e)
  3474. compute_utils.notify_usage_exists(self.notifier, context, instance,
  3475. self.host, current_period=True)
  3476. instance.vm_state = vm_states.RESCUED
  3477. instance.task_state = None
  3478. instance.power_state = self._get_power_state(context, instance)
  3479. instance.launched_at = timeutils.utcnow()
  3480. instance.save(expected_task_state=task_states.RESCUING)
  3481. self._notify_about_instance_usage(context, instance,
  3482. "rescue.end", extra_usage_info=extra_usage_info,
  3483. network_info=network_info)
  3484. compute_utils.notify_about_instance_rescue_action(
  3485. context, instance, self.host, rescue_image_ref,
  3486. phase=fields.NotificationPhase.END)
  3487. @wrap_exception()
  3488. @reverts_task_state
  3489. @wrap_instance_event(prefix='compute')
  3490. @wrap_instance_fault
  3491. def unrescue_instance(self, context, instance):
  3492. context = context.elevated()
  3493. LOG.info('Unrescuing', instance=instance)
  3494. network_info = self.network_api.get_instance_nw_info(context, instance)
  3495. self._notify_about_instance_usage(context, instance,
  3496. "unrescue.start", network_info=network_info)
  3497. compute_utils.notify_about_instance_action(context, instance,
  3498. self.host, action=fields.NotificationAction.UNRESCUE,
  3499. phase=fields.NotificationPhase.START)
  3500. with self._error_out_instance_on_exception(context, instance):
  3501. self.driver.unrescue(instance,
  3502. network_info)
  3503. instance.vm_state = vm_states.ACTIVE
  3504. instance.task_state = None
  3505. instance.power_state = self._get_power_state(context, instance)
  3506. instance.save(expected_task_state=task_states.UNRESCUING)
  3507. self._notify_about_instance_usage(context,
  3508. instance,
  3509. "unrescue.end",
  3510. network_info=network_info)
  3511. compute_utils.notify_about_instance_action(context, instance,
  3512. self.host, action=fields.NotificationAction.UNRESCUE,
  3513. phase=fields.NotificationPhase.END)
  3514. @wrap_exception()
  3515. @wrap_instance_fault
  3516. def change_instance_metadata(self, context, diff, instance):
  3517. """Update the metadata published to the instance."""
  3518. LOG.debug("Changing instance metadata according to %r",
  3519. diff, instance=instance)
  3520. self.driver.change_instance_metadata(context, instance, diff)
  3521. @wrap_exception()
  3522. @wrap_instance_event(prefix='compute')
  3523. @errors_out_migration
  3524. @wrap_instance_fault
  3525. def confirm_resize(self, context, instance, migration):
  3526. """Confirms a migration/resize and deletes the 'old' instance.
  3527. This is called from the API and runs on the source host.
  3528. Nothing needs to happen on the destination host at this point since
  3529. the instance is already running there. This routine just cleans up the
  3530. source host.
  3531. """
  3532. @utils.synchronized(instance.uuid)
  3533. def do_confirm_resize(context, instance, migration_id):
  3534. # NOTE(wangpan): Get the migration status from db, if it has been
  3535. # confirmed, we do nothing and return here
  3536. LOG.debug("Going to confirm migration %s", migration_id,
  3537. instance=instance)
  3538. try:
  3539. # TODO(russellb) Why are we sending the migration object just
  3540. # to turn around and look it up from the db again?
  3541. migration = objects.Migration.get_by_id(
  3542. context.elevated(), migration_id)
  3543. except exception.MigrationNotFound:
  3544. LOG.error("Migration %s is not found during confirmation",
  3545. migration_id, instance=instance)
  3546. return
  3547. if migration.status == 'confirmed':
  3548. LOG.info("Migration %s is already confirmed",
  3549. migration_id, instance=instance)
  3550. return
  3551. elif migration.status not in ('finished', 'confirming'):
  3552. LOG.warning("Unexpected confirmation status '%(status)s' "
  3553. "of migration %(id)s, exit confirmation process",
  3554. {"status": migration.status, "id": migration_id},
  3555. instance=instance)
  3556. return
  3557. # NOTE(wangpan): Get the instance from db, if it has been
  3558. # deleted, we do nothing and return here
  3559. expected_attrs = ['metadata', 'system_metadata', 'flavor']
  3560. try:
  3561. instance = objects.Instance.get_by_uuid(
  3562. context, instance.uuid,
  3563. expected_attrs=expected_attrs)
  3564. except exception.InstanceNotFound:
  3565. LOG.info("Instance is not found during confirmation",
  3566. instance=instance)
  3567. return
  3568. with self._error_out_instance_on_exception(context, instance):
  3569. old_instance_type = instance.old_flavor
  3570. try:
  3571. self._confirm_resize(
  3572. context, instance, migration=migration)
  3573. except Exception:
  3574. # Something failed when cleaning up the source host so
  3575. # log a traceback and leave a hint about hard rebooting
  3576. # the server to correct its state in the DB.
  3577. with excutils.save_and_reraise_exception(logger=LOG):
  3578. LOG.exception(
  3579. 'Confirm resize failed on source host %s. '
  3580. 'Resource allocations in the placement service '
  3581. 'will be removed regardless because the instance '
  3582. 'is now on the destination host %s. You can try '
  3583. 'hard rebooting the instance to correct its '
  3584. 'state.', self.host, migration.dest_compute,
  3585. instance=instance)
  3586. finally:
  3587. # Whether an error occurred or not, at this point the
  3588. # instance is on the dest host so to avoid leaking
  3589. # allocations in placement, delete them here.
  3590. # NOTE(mriedem): _delete_allocation_after_move is tightly
  3591. # coupled to the migration status on the confirm step so
  3592. # we unfortunately have to mutate the migration status to
  3593. # have _delete_allocation_after_move cleanup the allocation
  3594. # held by the migration consumer.
  3595. with utils.temporary_mutation(
  3596. migration, status='confirmed'):
  3597. self._delete_allocation_after_move(
  3598. context, instance, migration, old_instance_type,
  3599. migration.source_node)
  3600. do_confirm_resize(context, instance, migration.id)
  3601. def _get_updated_nw_info_with_pci_mapping(self, nw_info, pci_mapping):
  3602. # NOTE(adrianc): This method returns a copy of nw_info if modifications
  3603. # are made else it returns the original nw_info.
  3604. updated_nw_info = nw_info
  3605. if nw_info and pci_mapping:
  3606. updated_nw_info = copy.deepcopy(nw_info)
  3607. for vif in updated_nw_info:
  3608. if vif['vnic_type'] in network_model.VNIC_TYPES_SRIOV:
  3609. try:
  3610. vif_pci_addr = vif['profile']['pci_slot']
  3611. new_addr = pci_mapping[vif_pci_addr].address
  3612. vif['profile']['pci_slot'] = new_addr
  3613. LOG.debug("Updating VIF's PCI address for VIF %(id)s. "
  3614. "Original value %(orig_val)s, "
  3615. "new value %(new_val)s",
  3616. {'id': vif['id'],
  3617. 'orig_val': vif_pci_addr,
  3618. 'new_val': new_addr})
  3619. except (KeyError, AttributeError):
  3620. with excutils.save_and_reraise_exception():
  3621. # NOTE(adrianc): This should never happen. If we
  3622. # get here it means there is some inconsistency
  3623. # with either 'nw_info' or 'pci_mapping'.
  3624. LOG.error("Unexpected error when updating network "
  3625. "information with PCI mapping.")
  3626. return updated_nw_info
  3627. def _confirm_resize(self, context, instance, migration=None):
  3628. """Destroys the source instance."""
  3629. self._notify_about_instance_usage(context, instance,
  3630. "resize.confirm.start")
  3631. compute_utils.notify_about_instance_action(context, instance,
  3632. self.host, action=fields.NotificationAction.RESIZE_CONFIRM,
  3633. phase=fields.NotificationPhase.START)
  3634. # NOTE(danms): delete stashed migration information
  3635. old_instance_type = instance.old_flavor
  3636. instance.old_flavor = None
  3637. instance.new_flavor = None
  3638. instance.system_metadata.pop('old_vm_state', None)
  3639. instance.save()
  3640. # NOTE(tr3buchet): tear down networks on source host
  3641. self.network_api.setup_networks_on_host(context, instance,
  3642. migration.source_compute, teardown=True)
  3643. network_info = self.network_api.get_instance_nw_info(context,
  3644. instance)
  3645. # NOTE(adrianc): Populate old PCI device in VIF profile
  3646. # to allow virt driver to properly unplug it from Hypervisor.
  3647. pci_mapping = (instance.migration_context.
  3648. get_pci_mapping_for_migration(True))
  3649. network_info = self._get_updated_nw_info_with_pci_mapping(
  3650. network_info, pci_mapping)
  3651. # TODO(mriedem): Get BDMs here and pass them to the driver.
  3652. self.driver.confirm_migration(context, migration, instance,
  3653. network_info)
  3654. migration.status = 'confirmed'
  3655. with migration.obj_as_admin():
  3656. migration.save()
  3657. rt = self._get_resource_tracker()
  3658. rt.drop_move_claim(context, instance, migration.source_node,
  3659. old_instance_type, prefix='old_')
  3660. instance.drop_migration_context()
  3661. # NOTE(mriedem): The old_vm_state could be STOPPED but the user
  3662. # might have manually powered up the instance to confirm the
  3663. # resize/migrate, so we need to check the current power state
  3664. # on the instance and set the vm_state appropriately. We default
  3665. # to ACTIVE because if the power state is not SHUTDOWN, we
  3666. # assume _sync_instance_power_state will clean it up.
  3667. p_state = instance.power_state
  3668. vm_state = None
  3669. if p_state == power_state.SHUTDOWN:
  3670. vm_state = vm_states.STOPPED
  3671. LOG.debug("Resized/migrated instance is powered off. "
  3672. "Setting vm_state to '%s'.", vm_state,
  3673. instance=instance)
  3674. else:
  3675. vm_state = vm_states.ACTIVE
  3676. instance.vm_state = vm_state
  3677. instance.task_state = None
  3678. instance.save(expected_task_state=[None, task_states.DELETING,
  3679. task_states.SOFT_DELETING])
  3680. self._notify_about_instance_usage(
  3681. context, instance, "resize.confirm.end",
  3682. network_info=network_info)
  3683. compute_utils.notify_about_instance_action(context, instance,
  3684. self.host, action=fields.NotificationAction.RESIZE_CONFIRM,
  3685. phase=fields.NotificationPhase.END)
  3686. def _delete_allocation_after_move(self, context, instance, migration,
  3687. flavor, nodename):
  3688. rt = self._get_resource_tracker()
  3689. cn_uuid = rt.get_node_uuid(nodename)
  3690. if migration.source_node == nodename:
  3691. if migration.status in ('confirmed', 'completed'):
  3692. # NOTE(danms): We're finishing on the source node, so try to
  3693. # delete the allocation based on the migration uuid
  3694. deleted = self.reportclient.delete_allocation_for_instance(
  3695. context, migration.uuid)
  3696. if deleted:
  3697. LOG.info(_('Source node %(node)s confirmed migration '
  3698. '%(mig)s; deleted migration-based '
  3699. 'allocation'),
  3700. {'node': nodename, 'mig': migration.uuid})
  3701. # NOTE(danms): We succeeded, which means we do not
  3702. # need to do the complex double allocation dance
  3703. return
  3704. else:
  3705. # We're reverting (or failed) on the source, so we
  3706. # need to check if our migration holds a claim and if
  3707. # so, avoid doing the legacy behavior below.
  3708. mig_allocs = (
  3709. self.reportclient.get_allocations_for_consumer_by_provider(
  3710. context, cn_uuid, migration.uuid))
  3711. if mig_allocs:
  3712. LOG.info(_('Source node %(node)s reverted migration '
  3713. '%(mig)s; not deleting migration-based '
  3714. 'allocation'),
  3715. {'node': nodename, 'mig': migration.uuid})
  3716. return
  3717. elif migration.dest_node == nodename:
  3718. # NOTE(danms): We're reverting on the destination node
  3719. # (and we must not be doing a same-host migration if we
  3720. # made it past the check above), so we need to check to
  3721. # see if the source did migration-based allocation
  3722. # accounting
  3723. allocs = self.reportclient.get_allocations_for_consumer(
  3724. context, migration.uuid)
  3725. if allocs:
  3726. # NOTE(danms): The source did migration-based allocation
  3727. # accounting, so we should let the source node rejigger
  3728. # the allocations in finish_resize_revert()
  3729. LOG.info(_('Destination node %(node)s reverted migration '
  3730. '%(mig)s; not deleting migration-based '
  3731. 'allocation'),
  3732. {'node': nodename, 'mig': migration.uuid})
  3733. return
  3734. # TODO(danms): Remove below this line when we remove compatibility
  3735. # for double-accounting migrations (likely rocky)
  3736. LOG.info(_('Doing legacy allocation math for migration %(mig)s after '
  3737. 'instance move'),
  3738. {'mig': migration.uuid},
  3739. instance=instance)
  3740. # NOTE(jaypipes): This sucks, but due to the fact that confirm_resize()
  3741. # only runs on the source host and revert_resize() runs on the
  3742. # destination host, we need to do this here. Basically, what we're
  3743. # doing here is grabbing the existing allocations for this instance
  3744. # from the placement API, dropping the resources in the doubled-up
  3745. # allocation set that refer to the source host UUID and calling PUT
  3746. # /allocations back to the placement API. The allocation that gets
  3747. # PUT'd back to placement will only include the destination host and
  3748. # any shared providers in the case of a confirm_resize operation and
  3749. # the source host and shared providers for a revert_resize operation..
  3750. if not scheduler_utils.remove_allocation_from_compute(
  3751. context, instance, cn_uuid, self.reportclient, flavor):
  3752. LOG.error("Failed to save manipulated allocation",
  3753. instance=instance)
  3754. @wrap_exception()
  3755. @reverts_task_state
  3756. @wrap_instance_event(prefix='compute')
  3757. @errors_out_migration
  3758. @wrap_instance_fault
  3759. def revert_resize(self, context, instance, migration):
  3760. """Destroys the new instance on the destination machine.
  3761. Reverts the model changes, and powers on the old instance on the
  3762. source machine.
  3763. """
  3764. # NOTE(comstud): A revert_resize is essentially a resize back to
  3765. # the old size, so we need to send a usage event here.
  3766. compute_utils.notify_usage_exists(self.notifier, context, instance,
  3767. self.host, current_period=True)
  3768. with self._error_out_instance_on_exception(context, instance):
  3769. # NOTE(tr3buchet): tear down networks on destination host
  3770. self.network_api.setup_networks_on_host(context, instance,
  3771. teardown=True)
  3772. migration_p = obj_base.obj_to_primitive(migration)
  3773. self.network_api.migrate_instance_start(context,
  3774. instance,
  3775. migration_p)
  3776. network_info = self.network_api.get_instance_nw_info(context,
  3777. instance)
  3778. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  3779. context, instance.uuid)
  3780. block_device_info = self._get_instance_block_device_info(
  3781. context, instance, bdms=bdms)
  3782. destroy_disks = not self._is_instance_storage_shared(
  3783. context, instance, host=migration.source_compute)
  3784. self.driver.destroy(context, instance, network_info,
  3785. block_device_info, destroy_disks)
  3786. self._terminate_volume_connections(context, instance, bdms)
  3787. migration.status = 'reverted'
  3788. with migration.obj_as_admin():
  3789. migration.save()
  3790. # NOTE(ndipanov): We need to do this here because dropping the
  3791. # claim means we lose the migration_context data. We really should
  3792. # fix this by moving the drop_move_claim call to the
  3793. # finish_revert_resize method as this is racy (revert is dropped,
  3794. # but instance resources will be tracked with the new flavor until
  3795. # it gets rolled back in finish_revert_resize, which is
  3796. # potentially wrong for a period of time).
  3797. instance.revert_migration_context()
  3798. instance.save()
  3799. rt = self._get_resource_tracker()
  3800. rt.drop_move_claim(context, instance, instance.node)
  3801. self._delete_allocation_after_move(context, instance, migration,
  3802. instance.flavor,
  3803. instance.node)
  3804. # RPC cast back to the source host to finish the revert there.
  3805. self.compute_rpcapi.finish_revert_resize(context, instance,
  3806. migration, migration.source_compute)
  3807. def _finish_revert_resize_network_migrate_finish(self, context, instance,
  3808. migration):
  3809. """Causes port binding to be updated. In some Neutron or port
  3810. configurations - see NetworkModel.get_bind_time_events() - we
  3811. expect the vif-plugged event from Neutron immediately and wait for it.
  3812. The rest of the time, the event is expected further along in the
  3813. virt driver, so we don't wait here.
  3814. :param context: The request context.
  3815. :param instance: The instance undergoing the revert resize.
  3816. :param migration: The Migration object of the resize being reverted.
  3817. :raises: eventlet.timeout.Timeout or
  3818. exception.VirtualInterfacePlugException.
  3819. """
  3820. network_info = instance.get_network_info()
  3821. events = []
  3822. deadline = CONF.vif_plugging_timeout
  3823. if deadline and utils.is_neutron() and network_info:
  3824. events = network_info.get_bind_time_events(migration)
  3825. if events:
  3826. LOG.debug('Will wait for bind-time events: %s', events)
  3827. error_cb = self._neutron_failed_migration_callback
  3828. try:
  3829. with self.virtapi.wait_for_instance_event(instance, events,
  3830. deadline=deadline,
  3831. error_callback=error_cb):
  3832. # NOTE(hanrong): we need to change migration.dest_compute to
  3833. # source host temporarily.
  3834. # "network_api.migrate_instance_finish" will setup the network
  3835. # for the instance on the destination host. For revert resize,
  3836. # the instance will back to the source host, the setup of the
  3837. # network for instance should be on the source host. So set
  3838. # the migration.dest_compute to source host at here.
  3839. with utils.temporary_mutation(
  3840. migration, dest_compute=migration.source_compute):
  3841. self.network_api.migrate_instance_finish(context,
  3842. instance,
  3843. migration)
  3844. except eventlet.timeout.Timeout:
  3845. with excutils.save_and_reraise_exception():
  3846. LOG.error('Timeout waiting for Neutron events: %s', events,
  3847. instance=instance)
  3848. @wrap_exception()
  3849. @reverts_task_state
  3850. @wrap_instance_event(prefix='compute')
  3851. @errors_out_migration
  3852. @wrap_instance_fault
  3853. def finish_revert_resize(self, context, instance, migration):
  3854. """Finishes the second half of reverting a resize on the source host.
  3855. Bring the original source instance state back (active/shutoff) and
  3856. revert the resized attributes in the database.
  3857. """
  3858. with self._error_out_instance_on_exception(context, instance):
  3859. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  3860. context, instance.uuid)
  3861. self._notify_about_instance_usage(
  3862. context, instance, "resize.revert.start")
  3863. compute_utils.notify_about_instance_action(context, instance,
  3864. self.host, action=fields.NotificationAction.RESIZE_REVERT,
  3865. phase=fields.NotificationPhase.START, bdms=bdms)
  3866. # NOTE(mriedem): delete stashed old_vm_state information; we
  3867. # default to ACTIVE for backwards compatibility if old_vm_state
  3868. # is not set
  3869. old_vm_state = instance.system_metadata.pop('old_vm_state',
  3870. vm_states.ACTIVE)
  3871. self._set_instance_info(instance, instance.old_flavor)
  3872. instance.old_flavor = None
  3873. instance.new_flavor = None
  3874. instance.host = migration.source_compute
  3875. instance.node = migration.source_node
  3876. instance.save()
  3877. self._revert_allocation(context, instance, migration)
  3878. self.network_api.setup_networks_on_host(context, instance,
  3879. migration.source_compute)
  3880. self._finish_revert_resize_network_migrate_finish(
  3881. context, instance, migration)
  3882. network_info = self.network_api.get_instance_nw_info(context,
  3883. instance)
  3884. # revert_resize deleted any volume attachments for the instance
  3885. # and created new ones to be used on this host, but we
  3886. # have to update those attachments with the host connector so the
  3887. # BDM.connection_info will get set in the call to
  3888. # _get_instance_block_device_info below with refresh_conn_info=True
  3889. # and then the volumes can be re-connected via the driver on this
  3890. # host.
  3891. self._update_volume_attachments(context, instance, bdms)
  3892. block_device_info = self._get_instance_block_device_info(
  3893. context, instance, refresh_conn_info=True, bdms=bdms)
  3894. power_on = old_vm_state != vm_states.STOPPED
  3895. self.driver.finish_revert_migration(context, instance,
  3896. network_info,
  3897. block_device_info, power_on)
  3898. instance.drop_migration_context()
  3899. instance.launched_at = timeutils.utcnow()
  3900. instance.save(expected_task_state=task_states.RESIZE_REVERTING)
  3901. # Complete any volume attachments so the volumes are in-use.
  3902. self._complete_volume_attachments(context, bdms)
  3903. # if the original vm state was STOPPED, set it back to STOPPED
  3904. LOG.info("Updating instance to original state: '%s'",
  3905. old_vm_state, instance=instance)
  3906. if power_on:
  3907. instance.vm_state = vm_states.ACTIVE
  3908. instance.task_state = None
  3909. instance.save()
  3910. else:
  3911. instance.task_state = task_states.POWERING_OFF
  3912. instance.save()
  3913. self.stop_instance(context, instance=instance,
  3914. clean_shutdown=True)
  3915. self._notify_about_instance_usage(
  3916. context, instance, "resize.revert.end")
  3917. compute_utils.notify_about_instance_action(context, instance,
  3918. self.host, action=fields.NotificationAction.RESIZE_REVERT,
  3919. phase=fields.NotificationPhase.END, bdms=bdms)
  3920. def _revert_allocation(self, context, instance, migration):
  3921. """Revert an allocation that is held by migration to our instance."""
  3922. # Fetch the original allocation that the instance had on the source
  3923. # node, which are now held by the migration
  3924. orig_alloc = self.reportclient.get_allocations_for_consumer(
  3925. context, migration.uuid)
  3926. if not orig_alloc:
  3927. # NOTE(danms): This migration did not do per-migration allocation
  3928. # accounting, so nothing to do here.
  3929. LOG.info('Old-style migration %(mig)s is being reverted; '
  3930. 'no migration claims found on original node '
  3931. 'to swap.',
  3932. {'mig': migration.uuid},
  3933. instance=instance)
  3934. return False
  3935. if len(orig_alloc) > 1:
  3936. # NOTE(danms): This may change later if we have other allocations
  3937. # against other providers that need to be held by the migration
  3938. # as well. Perhaps something like shared storage resources that
  3939. # will actually be duplicated during a resize type operation.
  3940. LOG.error('New-style migration %(mig)s has allocations against '
  3941. 'more than one provider %(rps)s. This should not be '
  3942. 'possible, but reverting it anyway.',
  3943. {'mig': migration.uuid,
  3944. 'rps': ','.join(orig_alloc.keys())},
  3945. instance=instance)
  3946. # We only have a claim against one provider, it is the source node
  3947. cn_uuid = list(orig_alloc.keys())[0]
  3948. # Get just the resources part of the one allocation we need below
  3949. orig_alloc = orig_alloc[cn_uuid].get('resources', {})
  3950. # FIXME(danms): This method is flawed in that it asssumes allocations
  3951. # against only one provider. So, this may overwite allocations against
  3952. # a shared provider, if we had one.
  3953. LOG.info('Swapping old allocation on %(node)s held by migration '
  3954. '%(mig)s for instance',
  3955. {'node': cn_uuid, 'mig': migration.uuid},
  3956. instance=instance)
  3957. # TODO(cdent): Should we be doing anything with return values here?
  3958. self.reportclient.set_and_clear_allocations(
  3959. context, cn_uuid, instance.uuid, orig_alloc, instance.project_id,
  3960. instance.user_id, consumer_to_clear=migration.uuid)
  3961. return True
  3962. def _prep_resize(self, context, image, instance, instance_type,
  3963. filter_properties, node, migration, clean_shutdown=True):
  3964. if not filter_properties:
  3965. filter_properties = {}
  3966. if not instance.host:
  3967. self._set_instance_obj_error_state(context, instance)
  3968. msg = _('Instance has no source host')
  3969. raise exception.MigrationError(reason=msg)
  3970. same_host = instance.host == self.host
  3971. # if the flavor IDs match, it's migrate; otherwise resize
  3972. if same_host and instance_type.id == instance['instance_type_id']:
  3973. # check driver whether support migrate to same host
  3974. if not self.driver.capabilities.get(
  3975. 'supports_migrate_to_same_host', False):
  3976. raise exception.UnableToMigrateToSelf(
  3977. instance_id=instance.uuid, host=self.host)
  3978. # NOTE(danms): Stash the new instance_type to avoid having to
  3979. # look it up in the database later
  3980. instance.new_flavor = instance_type
  3981. # NOTE(mriedem): Stash the old vm_state so we can set the
  3982. # resized/reverted instance back to the same state later.
  3983. vm_state = instance.vm_state
  3984. LOG.debug('Stashing vm_state: %s', vm_state, instance=instance)
  3985. instance.system_metadata['old_vm_state'] = vm_state
  3986. instance.save()
  3987. limits = filter_properties.get('limits', {})
  3988. rt = self._get_resource_tracker()
  3989. with rt.resize_claim(context, instance, instance_type, node,
  3990. migration, image_meta=image,
  3991. limits=limits) as claim:
  3992. LOG.info('Migrating', instance=instance)
  3993. # RPC cast to the source host to start the actual resize/migration.
  3994. self.compute_rpcapi.resize_instance(
  3995. context, instance, claim.migration, image,
  3996. instance_type, clean_shutdown)
  3997. @wrap_exception()
  3998. @reverts_task_state
  3999. @wrap_instance_event(prefix='compute')
  4000. @wrap_instance_fault
  4001. def prep_resize(self, context, image, instance, instance_type,
  4002. request_spec, filter_properties, node,
  4003. clean_shutdown, migration, host_list):
  4004. """Initiates the process of moving a running instance to another host.
  4005. Possibly changes the VCPU, RAM and disk size in the process.
  4006. This is initiated from conductor and runs on the destination host.
  4007. The main purpose of this method is performing some checks on the
  4008. destination host and making a claim for resources. If the claim fails
  4009. then a reschedule to another host may be attempted which involves
  4010. calling back to conductor to start the process over again.
  4011. """
  4012. if node is None:
  4013. node = self._get_nodename(instance, refresh=True)
  4014. with self._error_out_instance_on_exception(context, instance), \
  4015. errors_out_migration_ctxt(migration):
  4016. compute_utils.notify_usage_exists(self.notifier, context, instance,
  4017. self.host, current_period=True)
  4018. self._notify_about_instance_usage(
  4019. context, instance, "resize.prep.start")
  4020. compute_utils.notify_about_resize_prep_instance(
  4021. context, instance, self.host,
  4022. fields.NotificationPhase.START, instance_type)
  4023. try:
  4024. self._prep_resize(context, image, instance,
  4025. instance_type, filter_properties,
  4026. node, migration, clean_shutdown)
  4027. except Exception:
  4028. # Since we hit a failure, we're either rescheduling or dead
  4029. # and either way we need to cleanup any allocations created
  4030. # by the scheduler for the destination node.
  4031. if migration and not self._revert_allocation(
  4032. context, instance, migration):
  4033. # We did not do a migration-based
  4034. # allocation. Note that for a resize to the
  4035. # same host, the scheduler will merge the
  4036. # flavors, so here we'd be subtracting the new
  4037. # flavor from the allocated resources on this
  4038. # node.
  4039. # FIXME(danms): Remove this in Rocky
  4040. rt = self._get_resource_tracker()
  4041. rt.delete_allocation_for_failed_resize(
  4042. context, instance, node, instance_type)
  4043. # try to re-schedule the resize elsewhere:
  4044. exc_info = sys.exc_info()
  4045. self._reschedule_resize_or_reraise(context, image, instance,
  4046. exc_info, instance_type, request_spec,
  4047. filter_properties, host_list)
  4048. finally:
  4049. extra_usage_info = dict(
  4050. new_instance_type=instance_type.name,
  4051. new_instance_type_id=instance_type.id)
  4052. self._notify_about_instance_usage(
  4053. context, instance, "resize.prep.end",
  4054. extra_usage_info=extra_usage_info)
  4055. compute_utils.notify_about_resize_prep_instance(
  4056. context, instance, self.host,
  4057. fields.NotificationPhase.END, instance_type)
  4058. def _reschedule_resize_or_reraise(self, context, image, instance, exc_info,
  4059. instance_type, request_spec, filter_properties, host_list):
  4060. """Try to re-schedule the resize or re-raise the original error to
  4061. error out the instance.
  4062. """
  4063. if not request_spec:
  4064. request_spec = {}
  4065. if not filter_properties:
  4066. filter_properties = {}
  4067. rescheduled = False
  4068. instance_uuid = instance.uuid
  4069. try:
  4070. reschedule_method = self.compute_task_api.resize_instance
  4071. scheduler_hint = dict(filter_properties=filter_properties)
  4072. method_args = (instance, None, scheduler_hint, instance_type)
  4073. task_state = task_states.RESIZE_PREP
  4074. rescheduled = self._reschedule(context, request_spec,
  4075. filter_properties, instance, reschedule_method,
  4076. method_args, task_state, exc_info, host_list=host_list)
  4077. except Exception as error:
  4078. rescheduled = False
  4079. LOG.exception("Error trying to reschedule",
  4080. instance_uuid=instance_uuid)
  4081. compute_utils.add_instance_fault_from_exc(context,
  4082. instance, error,
  4083. exc_info=sys.exc_info())
  4084. self._notify_about_instance_usage(context, instance,
  4085. 'resize.error', fault=error)
  4086. compute_utils.notify_about_instance_action(
  4087. context, instance, self.host,
  4088. action=fields.NotificationAction.RESIZE,
  4089. phase=fields.NotificationPhase.ERROR,
  4090. exception=error,
  4091. tb=','.join(traceback.format_exception(*exc_info)))
  4092. if rescheduled:
  4093. self._log_original_error(exc_info, instance_uuid)
  4094. compute_utils.add_instance_fault_from_exc(context,
  4095. instance, exc_info[1], exc_info=exc_info)
  4096. self._notify_about_instance_usage(context, instance,
  4097. 'resize.error', fault=exc_info[1])
  4098. compute_utils.notify_about_instance_action(
  4099. context, instance, self.host,
  4100. action=fields.NotificationAction.RESIZE,
  4101. phase=fields.NotificationPhase.ERROR,
  4102. exception=exc_info[1],
  4103. tb=','.join(traceback.format_exception(*exc_info)))
  4104. else:
  4105. # not re-scheduling
  4106. six.reraise(*exc_info)
  4107. @wrap_exception()
  4108. @reverts_task_state
  4109. @wrap_instance_event(prefix='compute')
  4110. @wrap_instance_fault
  4111. def resize_instance(self, context, instance, image,
  4112. migration, instance_type, clean_shutdown):
  4113. """Starts the migration of a running instance to another host.
  4114. This is initiated from the destination host's ``prep_resize`` routine
  4115. and runs on the source host.
  4116. """
  4117. try:
  4118. self._resize_instance(context, instance, image, migration,
  4119. instance_type, clean_shutdown)
  4120. except Exception:
  4121. with excutils.save_and_reraise_exception():
  4122. self._revert_allocation(context, instance, migration)
  4123. def _resize_instance(self, context, instance, image,
  4124. migration, instance_type, clean_shutdown):
  4125. with self._error_out_instance_on_exception(context, instance), \
  4126. errors_out_migration_ctxt(migration):
  4127. network_info = self.network_api.get_instance_nw_info(context,
  4128. instance)
  4129. migration.status = 'migrating'
  4130. with migration.obj_as_admin():
  4131. migration.save()
  4132. instance.task_state = task_states.RESIZE_MIGRATING
  4133. instance.save(expected_task_state=task_states.RESIZE_PREP)
  4134. self._notify_about_instance_usage(
  4135. context, instance, "resize.start", network_info=network_info)
  4136. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  4137. context, instance.uuid)
  4138. compute_utils.notify_about_instance_action(context, instance,
  4139. self.host, action=fields.NotificationAction.RESIZE,
  4140. phase=fields.NotificationPhase.START, bdms=bdms)
  4141. block_device_info = self._get_instance_block_device_info(
  4142. context, instance, bdms=bdms)
  4143. timeout, retry_interval = self._get_power_off_values(context,
  4144. instance, clean_shutdown)
  4145. disk_info = self.driver.migrate_disk_and_power_off(
  4146. context, instance, migration.dest_host,
  4147. instance_type, network_info,
  4148. block_device_info,
  4149. timeout, retry_interval)
  4150. self._terminate_volume_connections(context, instance, bdms)
  4151. migration_p = obj_base.obj_to_primitive(migration)
  4152. self.network_api.migrate_instance_start(context,
  4153. instance,
  4154. migration_p)
  4155. migration.status = 'post-migrating'
  4156. with migration.obj_as_admin():
  4157. migration.save()
  4158. instance.host = migration.dest_compute
  4159. instance.node = migration.dest_node
  4160. instance.task_state = task_states.RESIZE_MIGRATED
  4161. instance.save(expected_task_state=task_states.RESIZE_MIGRATING)
  4162. # RPC cast to the destination host to finish the resize/migration.
  4163. self.compute_rpcapi.finish_resize(context, instance,
  4164. migration, image, disk_info, migration.dest_compute)
  4165. self._notify_about_instance_usage(context, instance, "resize.end",
  4166. network_info=network_info)
  4167. compute_utils.notify_about_instance_action(context, instance,
  4168. self.host, action=fields.NotificationAction.RESIZE,
  4169. phase=fields.NotificationPhase.END, bdms=bdms)
  4170. self.instance_events.clear_events_for_instance(instance)
  4171. def _terminate_volume_connections(self, context, instance, bdms):
  4172. connector = None
  4173. for bdm in bdms:
  4174. if bdm.is_volume:
  4175. if bdm.attachment_id:
  4176. # NOTE(jdg): So here's the thing, the idea behind the new
  4177. # attach API's was to have a new code fork/path that we
  4178. # followed, we're not going to do that so we have to do
  4179. # some extra work in here to make it *behave* just like the
  4180. # old code. Cinder doesn't allow disconnect/reconnect (you
  4181. # just delete the attachment and get a new one)
  4182. # attachments in the new attach code so we have to do
  4183. # a delete and create without a connector (reserve),
  4184. # in other words, beware
  4185. attachment_id = self.volume_api.attachment_create(
  4186. context, bdm.volume_id, instance.uuid)['id']
  4187. self.volume_api.attachment_delete(context,
  4188. bdm.attachment_id)
  4189. bdm.attachment_id = attachment_id
  4190. bdm.save()
  4191. else:
  4192. if connector is None:
  4193. connector = self.driver.get_volume_connector(instance)
  4194. self.volume_api.terminate_connection(context,
  4195. bdm.volume_id,
  4196. connector)
  4197. @staticmethod
  4198. def _set_instance_info(instance, instance_type):
  4199. instance.instance_type_id = instance_type.id
  4200. instance.memory_mb = instance_type.memory_mb
  4201. instance.vcpus = instance_type.vcpus
  4202. instance.root_gb = instance_type.root_gb
  4203. instance.ephemeral_gb = instance_type.ephemeral_gb
  4204. instance.flavor = instance_type
  4205. def _update_volume_attachments(self, context, instance, bdms):
  4206. """Updates volume attachments using the virt driver host connector.
  4207. :param context: nova.context.RequestContext - user request context
  4208. :param instance: nova.objects.Instance
  4209. :param bdms: nova.objects.BlockDeviceMappingList - the list of block
  4210. device mappings for the given instance
  4211. """
  4212. if bdms:
  4213. connector = None
  4214. for bdm in bdms:
  4215. if bdm.is_volume and bdm.attachment_id:
  4216. if connector is None:
  4217. connector = self.driver.get_volume_connector(instance)
  4218. self.volume_api.attachment_update(
  4219. context, bdm.attachment_id, connector, bdm.device_name)
  4220. def _complete_volume_attachments(self, context, bdms):
  4221. """Completes volume attachments for the instance
  4222. :param context: nova.context.RequestContext - user request context
  4223. :param bdms: nova.objects.BlockDeviceMappingList - the list of block
  4224. device mappings for the given instance
  4225. """
  4226. if bdms:
  4227. for bdm in bdms:
  4228. if bdm.is_volume and bdm.attachment_id:
  4229. self.volume_api.attachment_complete(
  4230. context, bdm.attachment_id)
  4231. def _finish_resize(self, context, instance, migration, disk_info,
  4232. image_meta, bdms):
  4233. resize_instance = False
  4234. old_instance_type_id = migration['old_instance_type_id']
  4235. new_instance_type_id = migration['new_instance_type_id']
  4236. old_instance_type = instance.get_flavor()
  4237. # NOTE(mriedem): Get the old_vm_state so we know if we should
  4238. # power on the instance. If old_vm_state is not set we need to default
  4239. # to ACTIVE for backwards compatibility
  4240. old_vm_state = instance.system_metadata.get('old_vm_state',
  4241. vm_states.ACTIVE)
  4242. instance.old_flavor = old_instance_type
  4243. if old_instance_type_id != new_instance_type_id:
  4244. instance_type = instance.get_flavor('new')
  4245. self._set_instance_info(instance, instance_type)
  4246. for key in ('root_gb', 'swap', 'ephemeral_gb'):
  4247. if old_instance_type[key] != instance_type[key]:
  4248. resize_instance = True
  4249. break
  4250. instance.apply_migration_context()
  4251. # NOTE(tr3buchet): setup networks on destination host
  4252. self.network_api.setup_networks_on_host(context, instance,
  4253. migration['dest_compute'])
  4254. migration_p = obj_base.obj_to_primitive(migration)
  4255. self.network_api.migrate_instance_finish(context,
  4256. instance,
  4257. migration_p)
  4258. network_info = self.network_api.get_instance_nw_info(context, instance)
  4259. instance.task_state = task_states.RESIZE_FINISH
  4260. instance.save(expected_task_state=task_states.RESIZE_MIGRATED)
  4261. self._notify_about_instance_usage(
  4262. context, instance, "finish_resize.start",
  4263. network_info=network_info)
  4264. compute_utils.notify_about_instance_action(context, instance,
  4265. self.host, action=fields.NotificationAction.RESIZE_FINISH,
  4266. phase=fields.NotificationPhase.START, bdms=bdms)
  4267. # We need to update any volume attachments using the destination
  4268. # host connector so that we can update the BDM.connection_info
  4269. # before calling driver.finish_migration otherwise the driver
  4270. # won't know how to connect the volumes to this host.
  4271. # Note that _get_instance_block_device_info with
  4272. # refresh_conn_info=True will update the BDM.connection_info value
  4273. # in the database so we must do this before calling that method.
  4274. self._update_volume_attachments(context, instance, bdms)
  4275. block_device_info = self._get_instance_block_device_info(
  4276. context, instance, refresh_conn_info=True, bdms=bdms)
  4277. # NOTE(mriedem): If the original vm_state was STOPPED, we don't
  4278. # automatically power on the instance after it's migrated
  4279. power_on = old_vm_state != vm_states.STOPPED
  4280. try:
  4281. self.driver.finish_migration(context, migration, instance,
  4282. disk_info,
  4283. network_info,
  4284. image_meta, resize_instance,
  4285. block_device_info, power_on)
  4286. except Exception:
  4287. with excutils.save_and_reraise_exception():
  4288. if old_instance_type_id != new_instance_type_id:
  4289. self._set_instance_info(instance,
  4290. old_instance_type)
  4291. # Now complete any volume attachments that were previously updated.
  4292. self._complete_volume_attachments(context, bdms)
  4293. migration.status = 'finished'
  4294. with migration.obj_as_admin():
  4295. migration.save()
  4296. instance.vm_state = vm_states.RESIZED
  4297. instance.task_state = None
  4298. instance.launched_at = timeutils.utcnow()
  4299. instance.save(expected_task_state=task_states.RESIZE_FINISH)
  4300. return network_info
  4301. @wrap_exception()
  4302. @reverts_task_state
  4303. @wrap_instance_event(prefix='compute')
  4304. @wrap_instance_fault
  4305. def finish_resize(self, context, disk_info, image, instance,
  4306. migration):
  4307. """Completes the migration process.
  4308. Sets up the newly transferred disk and turns on the instance at its
  4309. new host machine.
  4310. """
  4311. # _finish_resize sets instance.old_flavor to instance.flavor and
  4312. # changes instance.flavor to instance.new_flavor (if doing a resize
  4313. # rather than a cold migration). We save off the old_flavor here in
  4314. # case we need it for error handling below.
  4315. old_flavor = instance.flavor
  4316. try:
  4317. self._finish_resize_helper(context, disk_info, image, instance,
  4318. migration)
  4319. except Exception:
  4320. with excutils.save_and_reraise_exception():
  4321. # At this point, resize_instance (which runs on the source) has
  4322. # already updated the instance host/node values to point to
  4323. # this (the dest) compute, so we need to leave the allocations
  4324. # against the dest node resource provider intact and drop the
  4325. # allocations against the source node resource provider. If the
  4326. # user tries to recover the server by hard rebooting it, it
  4327. # will happen on this host so that's where the allocations
  4328. # should go.
  4329. LOG.info('Deleting allocations for old flavor on source node '
  4330. '%s after finish_resize failure. You may be able to '
  4331. 'recover the instance by hard rebooting it.',
  4332. migration.source_compute, instance=instance)
  4333. # NOTE(mriedem): We can't use _delete_allocation_after_move
  4334. # because it relies on the resource tracker to look up the
  4335. # node uuid and since we are on the dest host, passing the
  4336. # source nodename won't work since the RT isn't tracking that
  4337. # node here. So we just try to remove the migration-based
  4338. # allocations directly and handle the case they don't exist.
  4339. if not self.reportclient.delete_allocation_for_instance(
  4340. context, migration.uuid):
  4341. # No migration-based allocation. Try to cleanup directly.
  4342. cn = objects.ComputeNode.get_by_host_and_nodename(
  4343. context, migration.source_compute,
  4344. migration.source_node)
  4345. if not scheduler_utils.remove_allocation_from_compute(
  4346. context, instance, cn.uuid, self.reportclient,
  4347. flavor=old_flavor):
  4348. LOG.error('Failed to delete allocations for old '
  4349. 'flavor %s against source node %s. The '
  4350. 'instance is now on the dest node %s. The '
  4351. 'allocations against the source node need '
  4352. 'to be manually cleaned up in Placement.',
  4353. old_flavor.flavorid, migration.source_node,
  4354. migration.dest_node, instance=instance)
  4355. def _finish_resize_helper(self, context, disk_info, image, instance,
  4356. migration):
  4357. """Completes the migration process.
  4358. The caller must revert the instance's allocations if the migration
  4359. process failed.
  4360. """
  4361. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  4362. context, instance.uuid)
  4363. with self._error_out_instance_on_exception(context, instance), \
  4364. errors_out_migration_ctxt(migration):
  4365. image_meta = objects.ImageMeta.from_dict(image)
  4366. network_info = self._finish_resize(context, instance, migration,
  4367. disk_info, image_meta, bdms)
  4368. # TODO(melwitt): We should clean up instance console tokens here. The
  4369. # instance is on a new host and will need to establish a new console
  4370. # connection.
  4371. self._update_scheduler_instance_info(context, instance)
  4372. self._notify_about_instance_usage(
  4373. context, instance, "finish_resize.end",
  4374. network_info=network_info)
  4375. compute_utils.notify_about_instance_action(context, instance,
  4376. self.host, action=fields.NotificationAction.RESIZE_FINISH,
  4377. phase=fields.NotificationPhase.END, bdms=bdms)
  4378. @wrap_exception()
  4379. @wrap_instance_fault
  4380. def add_fixed_ip_to_instance(self, context, network_id, instance):
  4381. """Calls network_api to add new fixed_ip to instance
  4382. then injects the new network info and resets instance networking.
  4383. """
  4384. self._notify_about_instance_usage(
  4385. context, instance, "create_ip.start")
  4386. network_info = self.network_api.add_fixed_ip_to_instance(context,
  4387. instance,
  4388. network_id)
  4389. self._inject_network_info(context, instance, network_info)
  4390. self.reset_network(context, instance)
  4391. # NOTE(russellb) We just want to bump updated_at. See bug 1143466.
  4392. instance.updated_at = timeutils.utcnow()
  4393. instance.save()
  4394. self._notify_about_instance_usage(
  4395. context, instance, "create_ip.end", network_info=network_info)
  4396. @wrap_exception()
  4397. @wrap_instance_fault
  4398. def remove_fixed_ip_from_instance(self, context, address, instance):
  4399. """Calls network_api to remove existing fixed_ip from instance
  4400. by injecting the altered network info and resetting
  4401. instance networking.
  4402. """
  4403. self._notify_about_instance_usage(
  4404. context, instance, "delete_ip.start")
  4405. network_info = self.network_api.remove_fixed_ip_from_instance(context,
  4406. instance,
  4407. address)
  4408. self._inject_network_info(context, instance, network_info)
  4409. self.reset_network(context, instance)
  4410. # NOTE(russellb) We just want to bump updated_at. See bug 1143466.
  4411. instance.updated_at = timeutils.utcnow()
  4412. instance.save()
  4413. self._notify_about_instance_usage(
  4414. context, instance, "delete_ip.end", network_info=network_info)
  4415. @wrap_exception()
  4416. @reverts_task_state
  4417. @wrap_instance_event(prefix='compute')
  4418. @wrap_instance_fault
  4419. def pause_instance(self, context, instance):
  4420. """Pause an instance on this host."""
  4421. context = context.elevated()
  4422. LOG.info('Pausing', instance=instance)
  4423. self._notify_about_instance_usage(context, instance, 'pause.start')
  4424. compute_utils.notify_about_instance_action(context, instance,
  4425. self.host, action=fields.NotificationAction.PAUSE,
  4426. phase=fields.NotificationPhase.START)
  4427. self.driver.pause(instance)
  4428. instance.power_state = self._get_power_state(context, instance)
  4429. instance.vm_state = vm_states.PAUSED
  4430. instance.task_state = None
  4431. instance.save(expected_task_state=task_states.PAUSING)
  4432. self._notify_about_instance_usage(context, instance, 'pause.end')
  4433. compute_utils.notify_about_instance_action(context, instance,
  4434. self.host, action=fields.NotificationAction.PAUSE,
  4435. phase=fields.NotificationPhase.END)
  4436. @wrap_exception()
  4437. @reverts_task_state
  4438. @wrap_instance_event(prefix='compute')
  4439. @wrap_instance_fault
  4440. def unpause_instance(self, context, instance):
  4441. """Unpause a paused instance on this host."""
  4442. context = context.elevated()
  4443. LOG.info('Unpausing', instance=instance)
  4444. self._notify_about_instance_usage(context, instance, 'unpause.start')
  4445. compute_utils.notify_about_instance_action(context, instance,
  4446. self.host, action=fields.NotificationAction.UNPAUSE,
  4447. phase=fields.NotificationPhase.START)
  4448. self.driver.unpause(instance)
  4449. instance.power_state = self._get_power_state(context, instance)
  4450. instance.vm_state = vm_states.ACTIVE
  4451. instance.task_state = None
  4452. instance.save(expected_task_state=task_states.UNPAUSING)
  4453. self._notify_about_instance_usage(context, instance, 'unpause.end')
  4454. compute_utils.notify_about_instance_action(context, instance,
  4455. self.host, action=fields.NotificationAction.UNPAUSE,
  4456. phase=fields.NotificationPhase.END)
  4457. @wrap_exception()
  4458. def host_power_action(self, context, action):
  4459. """Reboots, shuts down or powers up the host."""
  4460. return self.driver.host_power_action(action)
  4461. @wrap_exception()
  4462. def host_maintenance_mode(self, context, host, mode):
  4463. """Start/Stop host maintenance window. On start, it triggers
  4464. guest VMs evacuation.
  4465. """
  4466. return self.driver.host_maintenance_mode(host, mode)
  4467. @wrap_exception()
  4468. def set_host_enabled(self, context, enabled):
  4469. """Sets the specified host's ability to accept new instances."""
  4470. return self.driver.set_host_enabled(enabled)
  4471. @wrap_exception()
  4472. def get_host_uptime(self, context):
  4473. """Returns the result of calling "uptime" on the target host."""
  4474. return self.driver.get_host_uptime()
  4475. @wrap_exception()
  4476. @wrap_instance_fault
  4477. def get_diagnostics(self, context, instance):
  4478. """Retrieve diagnostics for an instance on this host."""
  4479. current_power_state = self._get_power_state(context, instance)
  4480. if current_power_state == power_state.RUNNING:
  4481. LOG.info("Retrieving diagnostics", instance=instance)
  4482. return self.driver.get_diagnostics(instance)
  4483. else:
  4484. raise exception.InstanceInvalidState(
  4485. attr='power state',
  4486. instance_uuid=instance.uuid,
  4487. state=power_state.STATE_MAP[instance.power_state],
  4488. method='get_diagnostics')
  4489. @wrap_exception()
  4490. @wrap_instance_fault
  4491. def get_instance_diagnostics(self, context, instance):
  4492. """Retrieve diagnostics for an instance on this host."""
  4493. current_power_state = self._get_power_state(context, instance)
  4494. if current_power_state == power_state.RUNNING:
  4495. LOG.info("Retrieving diagnostics", instance=instance)
  4496. return self.driver.get_instance_diagnostics(instance)
  4497. else:
  4498. raise exception.InstanceInvalidState(
  4499. attr='power state',
  4500. instance_uuid=instance.uuid,
  4501. state=power_state.STATE_MAP[instance.power_state],
  4502. method='get_diagnostics')
  4503. @wrap_exception()
  4504. @reverts_task_state
  4505. @wrap_instance_event(prefix='compute')
  4506. @wrap_instance_fault
  4507. def suspend_instance(self, context, instance):
  4508. """Suspend the given instance."""
  4509. context = context.elevated()
  4510. # Store the old state
  4511. instance.system_metadata['old_vm_state'] = instance.vm_state
  4512. self._notify_about_instance_usage(context, instance, 'suspend.start')
  4513. compute_utils.notify_about_instance_action(context, instance,
  4514. self.host, action=fields.NotificationAction.SUSPEND,
  4515. phase=fields.NotificationPhase.START)
  4516. with self._error_out_instance_on_exception(context, instance,
  4517. instance_state=instance.vm_state):
  4518. self.driver.suspend(context, instance)
  4519. instance.power_state = self._get_power_state(context, instance)
  4520. instance.vm_state = vm_states.SUSPENDED
  4521. instance.task_state = None
  4522. instance.save(expected_task_state=task_states.SUSPENDING)
  4523. self._notify_about_instance_usage(context, instance, 'suspend.end')
  4524. compute_utils.notify_about_instance_action(context, instance,
  4525. self.host, action=fields.NotificationAction.SUSPEND,
  4526. phase=fields.NotificationPhase.END)
  4527. @wrap_exception()
  4528. @reverts_task_state
  4529. @wrap_instance_event(prefix='compute')
  4530. @wrap_instance_fault
  4531. def resume_instance(self, context, instance):
  4532. """Resume the given suspended instance."""
  4533. context = context.elevated()
  4534. LOG.info('Resuming', instance=instance)
  4535. self._notify_about_instance_usage(context, instance, 'resume.start')
  4536. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  4537. context, instance.uuid)
  4538. block_device_info = self._get_instance_block_device_info(
  4539. context, instance, bdms=bdms)
  4540. compute_utils.notify_about_instance_action(context, instance,
  4541. self.host, action=fields.NotificationAction.RESUME,
  4542. phase=fields.NotificationPhase.START, bdms=bdms)
  4543. network_info = self.network_api.get_instance_nw_info(context, instance)
  4544. with self._error_out_instance_on_exception(context, instance,
  4545. instance_state=instance.vm_state):
  4546. self.driver.resume(context, instance, network_info,
  4547. block_device_info)
  4548. instance.power_state = self._get_power_state(context, instance)
  4549. # We default to the ACTIVE state for backwards compatibility
  4550. instance.vm_state = instance.system_metadata.pop('old_vm_state',
  4551. vm_states.ACTIVE)
  4552. instance.task_state = None
  4553. instance.save(expected_task_state=task_states.RESUMING)
  4554. self._notify_about_instance_usage(context, instance, 'resume.end')
  4555. compute_utils.notify_about_instance_action(context, instance,
  4556. self.host, action=fields.NotificationAction.RESUME,
  4557. phase=fields.NotificationPhase.END, bdms=bdms)
  4558. @wrap_exception()
  4559. @reverts_task_state
  4560. @wrap_instance_event(prefix='compute')
  4561. @wrap_instance_fault
  4562. def shelve_instance(self, context, instance, image_id,
  4563. clean_shutdown):
  4564. """Shelve an instance.
  4565. This should be used when you want to take a snapshot of the instance.
  4566. It also adds system_metadata that can be used by a periodic task to
  4567. offload the shelved instance after a period of time.
  4568. :param context: request context
  4569. :param instance: an Instance object
  4570. :param image_id: an image id to snapshot to.
  4571. :param clean_shutdown: give the GuestOS a chance to stop
  4572. """
  4573. @utils.synchronized(instance.uuid)
  4574. def do_shelve_instance():
  4575. self._shelve_instance(context, instance, image_id, clean_shutdown)
  4576. do_shelve_instance()
  4577. def _shelve_instance(self, context, instance, image_id,
  4578. clean_shutdown):
  4579. LOG.info('Shelving', instance=instance)
  4580. offload = CONF.shelved_offload_time == 0
  4581. if offload:
  4582. # Get the BDMs early so we can pass them into versioned
  4583. # notifications since _shelve_offload_instance needs the
  4584. # BDMs anyway.
  4585. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  4586. context, instance.uuid)
  4587. else:
  4588. bdms = None
  4589. compute_utils.notify_usage_exists(self.notifier, context, instance,
  4590. self.host, current_period=True)
  4591. self._notify_about_instance_usage(context, instance, 'shelve.start')
  4592. compute_utils.notify_about_instance_action(context, instance,
  4593. self.host, action=fields.NotificationAction.SHELVE,
  4594. phase=fields.NotificationPhase.START, bdms=bdms)
  4595. def update_task_state(task_state, expected_state=task_states.SHELVING):
  4596. shelving_state_map = {
  4597. task_states.IMAGE_PENDING_UPLOAD:
  4598. task_states.SHELVING_IMAGE_PENDING_UPLOAD,
  4599. task_states.IMAGE_UPLOADING:
  4600. task_states.SHELVING_IMAGE_UPLOADING,
  4601. task_states.SHELVING: task_states.SHELVING}
  4602. task_state = shelving_state_map[task_state]
  4603. expected_state = shelving_state_map[expected_state]
  4604. instance.task_state = task_state
  4605. instance.save(expected_task_state=expected_state)
  4606. # Do not attempt a clean shutdown of a paused guest since some
  4607. # hypervisors will fail the clean shutdown if the guest is not
  4608. # running.
  4609. if instance.power_state == power_state.PAUSED:
  4610. clean_shutdown = False
  4611. self._power_off_instance(context, instance, clean_shutdown)
  4612. self.driver.snapshot(context, instance, image_id, update_task_state)
  4613. instance.system_metadata['shelved_at'] = timeutils.utcnow().isoformat()
  4614. instance.system_metadata['shelved_image_id'] = image_id
  4615. instance.system_metadata['shelved_host'] = self.host
  4616. instance.vm_state = vm_states.SHELVED
  4617. instance.task_state = None
  4618. if CONF.shelved_offload_time == 0:
  4619. instance.task_state = task_states.SHELVING_OFFLOADING
  4620. instance.power_state = self._get_power_state(context, instance)
  4621. instance.save(expected_task_state=[
  4622. task_states.SHELVING,
  4623. task_states.SHELVING_IMAGE_UPLOADING])
  4624. self._notify_about_instance_usage(context, instance, 'shelve.end')
  4625. compute_utils.notify_about_instance_action(context, instance,
  4626. self.host, action=fields.NotificationAction.SHELVE,
  4627. phase=fields.NotificationPhase.END, bdms=bdms)
  4628. if offload:
  4629. self._shelve_offload_instance(context, instance,
  4630. clean_shutdown=False, bdms=bdms)
  4631. @wrap_exception()
  4632. @reverts_task_state
  4633. @wrap_instance_event(prefix='compute')
  4634. @wrap_instance_fault
  4635. def shelve_offload_instance(self, context, instance, clean_shutdown):
  4636. """Remove a shelved instance from the hypervisor.
  4637. This frees up those resources for use by other instances, but may lead
  4638. to slower unshelve times for this instance. This method is used by
  4639. volume backed instances since restoring them doesn't involve the
  4640. potentially large download of an image.
  4641. :param context: request context
  4642. :param instance: nova.objects.instance.Instance
  4643. :param clean_shutdown: give the GuestOS a chance to stop
  4644. """
  4645. @utils.synchronized(instance.uuid)
  4646. def do_shelve_offload_instance():
  4647. self._shelve_offload_instance(context, instance, clean_shutdown)
  4648. do_shelve_offload_instance()
  4649. def _shelve_offload_instance(self, context, instance, clean_shutdown,
  4650. bdms=None):
  4651. LOG.info('Shelve offloading', instance=instance)
  4652. if bdms is None:
  4653. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  4654. context, instance.uuid)
  4655. self._notify_about_instance_usage(context, instance,
  4656. 'shelve_offload.start')
  4657. compute_utils.notify_about_instance_action(context, instance,
  4658. self.host, action=fields.NotificationAction.SHELVE_OFFLOAD,
  4659. phase=fields.NotificationPhase.START, bdms=bdms)
  4660. self._power_off_instance(context, instance, clean_shutdown)
  4661. current_power_state = self._get_power_state(context, instance)
  4662. self.network_api.cleanup_instance_network_on_host(context, instance,
  4663. instance.host)
  4664. network_info = self.network_api.get_instance_nw_info(context, instance)
  4665. block_device_info = self._get_instance_block_device_info(context,
  4666. instance,
  4667. bdms=bdms)
  4668. self.driver.destroy(context, instance, network_info,
  4669. block_device_info)
  4670. # the instance is going to be removed from the host so we want to
  4671. # terminate all the connections with the volume server and the host
  4672. self._terminate_volume_connections(context, instance, bdms)
  4673. instance.power_state = current_power_state
  4674. # NOTE(mriedem): The vm_state has to be set before updating the
  4675. # resource tracker, see vm_states.ALLOW_RESOURCE_REMOVAL. The host/node
  4676. # values cannot be nulled out until after updating the resource tracker
  4677. # though.
  4678. instance.vm_state = vm_states.SHELVED_OFFLOADED
  4679. instance.task_state = None
  4680. instance.save(expected_task_state=[task_states.SHELVING,
  4681. task_states.SHELVING_OFFLOADING])
  4682. # NOTE(ndipanov): Free resources from the resource tracker
  4683. self._update_resource_tracker(context, instance)
  4684. rt = self._get_resource_tracker()
  4685. rt.delete_allocation_for_shelve_offloaded_instance(context, instance)
  4686. # NOTE(sfinucan): RPC calls should no longer be attempted against this
  4687. # instance, so ensure any calls result in errors
  4688. self._nil_out_instance_obj_host_and_node(instance)
  4689. instance.save(expected_task_state=None)
  4690. # TODO(melwitt): We should clean up instance console tokens here. The
  4691. # instance has no host at this point and will need to establish a new
  4692. # console connection in the future after it is unshelved.
  4693. self._delete_scheduler_instance_info(context, instance.uuid)
  4694. self._notify_about_instance_usage(context, instance,
  4695. 'shelve_offload.end')
  4696. compute_utils.notify_about_instance_action(context, instance,
  4697. self.host, action=fields.NotificationAction.SHELVE_OFFLOAD,
  4698. phase=fields.NotificationPhase.END, bdms=bdms)
  4699. @wrap_exception()
  4700. @reverts_task_state
  4701. @wrap_instance_event(prefix='compute')
  4702. @wrap_instance_fault
  4703. def unshelve_instance(self, context, instance, image,
  4704. filter_properties, node):
  4705. """Unshelve the instance.
  4706. :param context: request context
  4707. :param instance: a nova.objects.instance.Instance object
  4708. :param image: an image to build from. If None we assume a
  4709. volume backed instance.
  4710. :param filter_properties: dict containing limits, retry info etc.
  4711. :param node: target compute node
  4712. """
  4713. if filter_properties is None:
  4714. filter_properties = {}
  4715. @utils.synchronized(instance.uuid)
  4716. def do_unshelve_instance():
  4717. self._unshelve_instance(context, instance, image,
  4718. filter_properties, node)
  4719. do_unshelve_instance()
  4720. def _unshelve_instance_key_scrub(self, instance):
  4721. """Remove data from the instance that may cause side effects."""
  4722. cleaned_keys = dict(
  4723. key_data=instance.key_data,
  4724. auto_disk_config=instance.auto_disk_config)
  4725. instance.key_data = None
  4726. instance.auto_disk_config = False
  4727. return cleaned_keys
  4728. def _unshelve_instance_key_restore(self, instance, keys):
  4729. """Restore previously scrubbed keys before saving the instance."""
  4730. instance.update(keys)
  4731. def _unshelve_instance(self, context, instance, image, filter_properties,
  4732. node):
  4733. LOG.info('Unshelving', instance=instance)
  4734. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  4735. context, instance.uuid)
  4736. self._notify_about_instance_usage(context, instance, 'unshelve.start')
  4737. compute_utils.notify_about_instance_action(context, instance,
  4738. self.host, action=fields.NotificationAction.UNSHELVE,
  4739. phase=fields.NotificationPhase.START, bdms=bdms)
  4740. instance.task_state = task_states.SPAWNING
  4741. instance.save()
  4742. block_device_info = self._prep_block_device(context, instance, bdms)
  4743. scrubbed_keys = self._unshelve_instance_key_scrub(instance)
  4744. if node is None:
  4745. node = self._get_nodename(instance)
  4746. rt = self._get_resource_tracker()
  4747. limits = filter_properties.get('limits', {})
  4748. allocations = self.reportclient.get_allocations_for_consumer(
  4749. context, instance.uuid)
  4750. shelved_image_ref = instance.image_ref
  4751. if image:
  4752. instance.image_ref = image['id']
  4753. image_meta = objects.ImageMeta.from_dict(image)
  4754. else:
  4755. image_meta = objects.ImageMeta.from_dict(
  4756. utils.get_image_from_system_metadata(
  4757. instance.system_metadata))
  4758. self.network_api.setup_instance_network_on_host(context, instance,
  4759. self.host)
  4760. network_info = self.network_api.get_instance_nw_info(context, instance)
  4761. try:
  4762. with rt.instance_claim(context, instance, node, limits):
  4763. self.driver.spawn(context, instance, image_meta,
  4764. injected_files=[],
  4765. admin_password=None,
  4766. allocations=allocations,
  4767. network_info=network_info,
  4768. block_device_info=block_device_info)
  4769. except Exception:
  4770. with excutils.save_and_reraise_exception(logger=LOG):
  4771. LOG.exception('Instance failed to spawn',
  4772. instance=instance)
  4773. # Cleanup allocations created by the scheduler on this host
  4774. # since we failed to spawn the instance. We do this both if
  4775. # the instance claim failed with ComputeResourcesUnavailable
  4776. # or if we did claim but the spawn failed, because aborting the
  4777. # instance claim will not remove the allocations.
  4778. rt.reportclient.delete_allocation_for_instance(context,
  4779. instance.uuid)
  4780. # FIXME: Umm, shouldn't we be rolling back port bindings too?
  4781. self._terminate_volume_connections(context, instance, bdms)
  4782. # The reverts_task_state decorator on unshelve_instance will
  4783. # eventually save these updates.
  4784. self._nil_out_instance_obj_host_and_node(instance)
  4785. if image:
  4786. instance.image_ref = shelved_image_ref
  4787. self._delete_snapshot_of_shelved_instance(context, instance,
  4788. image['id'])
  4789. self._unshelve_instance_key_restore(instance, scrubbed_keys)
  4790. self._update_instance_after_spawn(context, instance)
  4791. # Delete system_metadata for a shelved instance
  4792. compute_utils.remove_shelved_keys_from_system_metadata(instance)
  4793. instance.save(expected_task_state=task_states.SPAWNING)
  4794. self._update_scheduler_instance_info(context, instance)
  4795. self._notify_about_instance_usage(context, instance, 'unshelve.end')
  4796. compute_utils.notify_about_instance_action(context, instance,
  4797. self.host, action=fields.NotificationAction.UNSHELVE,
  4798. phase=fields.NotificationPhase.END, bdms=bdms)
  4799. @messaging.expected_exceptions(NotImplementedError)
  4800. @wrap_instance_fault
  4801. def reset_network(self, context, instance):
  4802. """Reset networking on the given instance."""
  4803. LOG.debug('Reset network', instance=instance)
  4804. self.driver.reset_network(instance)
  4805. def _inject_network_info(self, context, instance, network_info):
  4806. """Inject network info for the given instance."""
  4807. LOG.debug('Inject network info', instance=instance)
  4808. LOG.debug('network_info to inject: |%s|', network_info,
  4809. instance=instance)
  4810. self.driver.inject_network_info(instance,
  4811. network_info)
  4812. @wrap_instance_fault
  4813. def inject_network_info(self, context, instance):
  4814. """Inject network info, but don't return the info."""
  4815. network_info = self.network_api.get_instance_nw_info(context, instance)
  4816. self._inject_network_info(context, instance, network_info)
  4817. @messaging.expected_exceptions(NotImplementedError,
  4818. exception.ConsoleNotAvailable,
  4819. exception.InstanceNotFound)
  4820. @wrap_exception()
  4821. @wrap_instance_fault
  4822. def get_console_output(self, context, instance, tail_length):
  4823. """Send the console output for the given instance."""
  4824. context = context.elevated()
  4825. LOG.info("Get console output", instance=instance)
  4826. output = self.driver.get_console_output(context, instance)
  4827. if type(output) is six.text_type:
  4828. output = six.b(output)
  4829. if tail_length is not None:
  4830. output = self._tail_log(output, tail_length)
  4831. return output.decode('ascii', 'replace')
  4832. def _tail_log(self, log, length):
  4833. try:
  4834. length = int(length)
  4835. except ValueError:
  4836. length = 0
  4837. if length == 0:
  4838. return b''
  4839. else:
  4840. return b'\n'.join(log.split(b'\n')[-int(length):])
  4841. @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
  4842. exception.InstanceNotReady,
  4843. exception.InstanceNotFound,
  4844. exception.ConsoleTypeUnavailable,
  4845. NotImplementedError)
  4846. @wrap_exception()
  4847. @wrap_instance_fault
  4848. def get_vnc_console(self, context, console_type, instance):
  4849. """Return connection information for a vnc console."""
  4850. context = context.elevated()
  4851. LOG.debug("Getting vnc console", instance=instance)
  4852. if not CONF.vnc.enabled:
  4853. raise exception.ConsoleTypeUnavailable(console_type=console_type)
  4854. if console_type == 'novnc':
  4855. # For essex, novncproxy_base_url must include the full path
  4856. # including the html file (like http://myhost/vnc_auto.html)
  4857. access_url_base = CONF.vnc.novncproxy_base_url
  4858. elif console_type == 'xvpvnc':
  4859. access_url_base = CONF.vnc.xvpvncproxy_base_url
  4860. else:
  4861. raise exception.ConsoleTypeInvalid(console_type=console_type)
  4862. try:
  4863. # Retrieve connect info from driver, and then decorate with our
  4864. # access info token
  4865. console = self.driver.get_vnc_console(context, instance)
  4866. console_auth = objects.ConsoleAuthToken(
  4867. context=context,
  4868. console_type=console_type,
  4869. host=console.host,
  4870. port=console.port,
  4871. internal_access_path=console.internal_access_path,
  4872. instance_uuid=instance.uuid,
  4873. access_url_base=access_url_base,
  4874. )
  4875. console_auth.authorize(CONF.consoleauth.token_ttl)
  4876. connect_info = console.get_connection_info(
  4877. console_auth.token, console_auth.access_url)
  4878. except exception.InstanceNotFound:
  4879. if instance.vm_state != vm_states.BUILDING:
  4880. raise
  4881. raise exception.InstanceNotReady(instance_id=instance.uuid)
  4882. return connect_info
  4883. @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
  4884. exception.InstanceNotReady,
  4885. exception.InstanceNotFound,
  4886. exception.ConsoleTypeUnavailable,
  4887. NotImplementedError)
  4888. @wrap_exception()
  4889. @wrap_instance_fault
  4890. def get_spice_console(self, context, console_type, instance):
  4891. """Return connection information for a spice console."""
  4892. context = context.elevated()
  4893. LOG.debug("Getting spice console", instance=instance)
  4894. if not CONF.spice.enabled:
  4895. raise exception.ConsoleTypeUnavailable(console_type=console_type)
  4896. if console_type != 'spice-html5':
  4897. raise exception.ConsoleTypeInvalid(console_type=console_type)
  4898. try:
  4899. # Retrieve connect info from driver, and then decorate with our
  4900. # access info token
  4901. console = self.driver.get_spice_console(context, instance)
  4902. console_auth = objects.ConsoleAuthToken(
  4903. context=context,
  4904. console_type=console_type,
  4905. host=console.host,
  4906. port=console.port,
  4907. internal_access_path=console.internal_access_path,
  4908. instance_uuid=instance.uuid,
  4909. access_url_base=CONF.spice.html5proxy_base_url,
  4910. )
  4911. console_auth.authorize(CONF.consoleauth.token_ttl)
  4912. connect_info = console.get_connection_info(
  4913. console_auth.token, console_auth.access_url)
  4914. except exception.InstanceNotFound:
  4915. if instance.vm_state != vm_states.BUILDING:
  4916. raise
  4917. raise exception.InstanceNotReady(instance_id=instance.uuid)
  4918. return connect_info
  4919. @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
  4920. exception.InstanceNotReady,
  4921. exception.InstanceNotFound,
  4922. exception.ConsoleTypeUnavailable,
  4923. NotImplementedError)
  4924. @wrap_exception()
  4925. @wrap_instance_fault
  4926. def get_rdp_console(self, context, console_type, instance):
  4927. """Return connection information for a RDP console."""
  4928. context = context.elevated()
  4929. LOG.debug("Getting RDP console", instance=instance)
  4930. if not CONF.rdp.enabled:
  4931. raise exception.ConsoleTypeUnavailable(console_type=console_type)
  4932. if console_type != 'rdp-html5':
  4933. raise exception.ConsoleTypeInvalid(console_type=console_type)
  4934. try:
  4935. # Retrieve connect info from driver, and then decorate with our
  4936. # access info token
  4937. console = self.driver.get_rdp_console(context, instance)
  4938. console_auth = objects.ConsoleAuthToken(
  4939. context=context,
  4940. console_type=console_type,
  4941. host=console.host,
  4942. port=console.port,
  4943. internal_access_path=console.internal_access_path,
  4944. instance_uuid=instance.uuid,
  4945. access_url_base=CONF.rdp.html5_proxy_base_url,
  4946. )
  4947. console_auth.authorize(CONF.consoleauth.token_ttl)
  4948. connect_info = console.get_connection_info(
  4949. console_auth.token, console_auth.access_url)
  4950. except exception.InstanceNotFound:
  4951. if instance.vm_state != vm_states.BUILDING:
  4952. raise
  4953. raise exception.InstanceNotReady(instance_id=instance.uuid)
  4954. return connect_info
  4955. @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
  4956. exception.InstanceNotReady,
  4957. exception.InstanceNotFound,
  4958. exception.ConsoleTypeUnavailable,
  4959. NotImplementedError)
  4960. @wrap_exception()
  4961. @wrap_instance_fault
  4962. def get_mks_console(self, context, console_type, instance):
  4963. """Return connection information for a MKS console."""
  4964. context = context.elevated()
  4965. LOG.debug("Getting MKS console", instance=instance)
  4966. if not CONF.mks.enabled:
  4967. raise exception.ConsoleTypeUnavailable(console_type=console_type)
  4968. if console_type != 'webmks':
  4969. raise exception.ConsoleTypeInvalid(console_type=console_type)
  4970. try:
  4971. # Retrieve connect info from driver, and then decorate with our
  4972. # access info token
  4973. console = self.driver.get_mks_console(context, instance)
  4974. console_auth = objects.ConsoleAuthToken(
  4975. context=context,
  4976. console_type=console_type,
  4977. host=console.host,
  4978. port=console.port,
  4979. internal_access_path=console.internal_access_path,
  4980. instance_uuid=instance.uuid,
  4981. access_url_base=CONF.mks.mksproxy_base_url,
  4982. )
  4983. console_auth.authorize(CONF.consoleauth.token_ttl)
  4984. connect_info = console.get_connection_info(
  4985. console_auth.token, console_auth.access_url)
  4986. except exception.InstanceNotFound:
  4987. if instance.vm_state != vm_states.BUILDING:
  4988. raise
  4989. raise exception.InstanceNotReady(instance_id=instance.uuid)
  4990. return connect_info
  4991. @messaging.expected_exceptions(
  4992. exception.ConsoleTypeInvalid,
  4993. exception.InstanceNotReady,
  4994. exception.InstanceNotFound,
  4995. exception.ConsoleTypeUnavailable,
  4996. exception.SocketPortRangeExhaustedException,
  4997. exception.ImageSerialPortNumberInvalid,
  4998. exception.ImageSerialPortNumberExceedFlavorValue,
  4999. NotImplementedError)
  5000. @wrap_exception()
  5001. @wrap_instance_fault
  5002. def get_serial_console(self, context, console_type, instance):
  5003. """Returns connection information for a serial console."""
  5004. LOG.debug("Getting serial console", instance=instance)
  5005. if not CONF.serial_console.enabled:
  5006. raise exception.ConsoleTypeUnavailable(console_type=console_type)
  5007. context = context.elevated()
  5008. try:
  5009. # Retrieve connect info from driver, and then decorate with our
  5010. # access info token
  5011. console = self.driver.get_serial_console(context, instance)
  5012. console_auth = objects.ConsoleAuthToken(
  5013. context=context,
  5014. console_type=console_type,
  5015. host=console.host,
  5016. port=console.port,
  5017. internal_access_path=console.internal_access_path,
  5018. instance_uuid=instance.uuid,
  5019. access_url_base=CONF.serial_console.base_url,
  5020. )
  5021. console_auth.authorize(CONF.consoleauth.token_ttl)
  5022. connect_info = console.get_connection_info(
  5023. console_auth.token, console_auth.access_url)
  5024. except exception.InstanceNotFound:
  5025. if instance.vm_state != vm_states.BUILDING:
  5026. raise
  5027. raise exception.InstanceNotReady(instance_id=instance.uuid)
  5028. return connect_info
  5029. @messaging.expected_exceptions(exception.ConsoleTypeInvalid,
  5030. exception.InstanceNotReady,
  5031. exception.InstanceNotFound)
  5032. @wrap_exception()
  5033. @wrap_instance_fault
  5034. def validate_console_port(self, ctxt, instance, port, console_type):
  5035. if console_type == "spice-html5":
  5036. console_info = self.driver.get_spice_console(ctxt, instance)
  5037. elif console_type == "rdp-html5":
  5038. console_info = self.driver.get_rdp_console(ctxt, instance)
  5039. elif console_type == "serial":
  5040. console_info = self.driver.get_serial_console(ctxt, instance)
  5041. elif console_type == "webmks":
  5042. console_info = self.driver.get_mks_console(ctxt, instance)
  5043. else:
  5044. console_info = self.driver.get_vnc_console(ctxt, instance)
  5045. # Some drivers may return an int on console_info.port but the port
  5046. # variable in this method is a string, so cast to be sure we are
  5047. # comparing the correct types.
  5048. return str(console_info.port) == port
  5049. @wrap_exception()
  5050. @reverts_task_state
  5051. @wrap_instance_fault
  5052. def reserve_block_device_name(self, context, instance, device,
  5053. volume_id, disk_bus, device_type, tag,
  5054. multiattach):
  5055. if (tag and not
  5056. self.driver.capabilities.get('supports_tagged_attach_volume',
  5057. False)):
  5058. raise exception.VolumeTaggedAttachNotSupported()
  5059. if (multiattach and not
  5060. self.driver.capabilities.get('supports_multiattach', False)):
  5061. raise exception.MultiattachNotSupportedByVirtDriver(
  5062. volume_id=volume_id)
  5063. @utils.synchronized(instance.uuid)
  5064. def do_reserve():
  5065. bdms = (
  5066. objects.BlockDeviceMappingList.get_by_instance_uuid(
  5067. context, instance.uuid))
  5068. # NOTE(ndipanov): We need to explicitly set all the fields on the
  5069. # object so that obj_load_attr does not fail
  5070. new_bdm = objects.BlockDeviceMapping(
  5071. context=context,
  5072. source_type='volume', destination_type='volume',
  5073. instance_uuid=instance.uuid, boot_index=None,
  5074. volume_id=volume_id,
  5075. device_name=device, guest_format=None,
  5076. disk_bus=disk_bus, device_type=device_type, tag=tag)
  5077. new_bdm.device_name = self._get_device_name_for_instance(
  5078. instance, bdms, new_bdm)
  5079. # NOTE(vish): create bdm here to avoid race condition
  5080. new_bdm.create()
  5081. return new_bdm
  5082. return do_reserve()
  5083. @wrap_exception()
  5084. @wrap_instance_event(prefix='compute')
  5085. @wrap_instance_fault
  5086. def attach_volume(self, context, instance, bdm):
  5087. """Attach a volume to an instance."""
  5088. driver_bdm = driver_block_device.convert_volume(bdm)
  5089. @utils.synchronized(instance.uuid)
  5090. def do_attach_volume(context, instance, driver_bdm):
  5091. try:
  5092. return self._attach_volume(context, instance, driver_bdm)
  5093. except Exception:
  5094. with excutils.save_and_reraise_exception():
  5095. bdm.destroy()
  5096. do_attach_volume(context, instance, driver_bdm)
  5097. def _attach_volume(self, context, instance, bdm):
  5098. context = context.elevated()
  5099. LOG.info('Attaching volume %(volume_id)s to %(mountpoint)s',
  5100. {'volume_id': bdm.volume_id,
  5101. 'mountpoint': bdm['mount_device']},
  5102. instance=instance)
  5103. compute_utils.notify_about_volume_attach_detach(
  5104. context, instance, self.host,
  5105. action=fields.NotificationAction.VOLUME_ATTACH,
  5106. phase=fields.NotificationPhase.START,
  5107. volume_id=bdm.volume_id)
  5108. try:
  5109. bdm.attach(context, instance, self.volume_api, self.driver,
  5110. do_driver_attach=True)
  5111. except Exception as e:
  5112. with excutils.save_and_reraise_exception():
  5113. LOG.exception("Failed to attach %(volume_id)s "
  5114. "at %(mountpoint)s",
  5115. {'volume_id': bdm.volume_id,
  5116. 'mountpoint': bdm['mount_device']},
  5117. instance=instance)
  5118. if bdm['attachment_id']:
  5119. # Try to delete the attachment to make the volume
  5120. # available again. Note that DriverVolumeBlockDevice
  5121. # may have already deleted the attachment so ignore
  5122. # VolumeAttachmentNotFound.
  5123. try:
  5124. self.volume_api.attachment_delete(
  5125. context, bdm['attachment_id'])
  5126. except exception.VolumeAttachmentNotFound as exc:
  5127. LOG.debug('Ignoring VolumeAttachmentNotFound: %s',
  5128. exc, instance=instance)
  5129. else:
  5130. self.volume_api.unreserve_volume(context, bdm.volume_id)
  5131. tb = traceback.format_exc()
  5132. compute_utils.notify_about_volume_attach_detach(
  5133. context, instance, self.host,
  5134. action=fields.NotificationAction.VOLUME_ATTACH,
  5135. phase=fields.NotificationPhase.ERROR,
  5136. exception=e,
  5137. volume_id=bdm.volume_id, tb=tb)
  5138. info = {'volume_id': bdm.volume_id}
  5139. self._notify_about_instance_usage(
  5140. context, instance, "volume.attach", extra_usage_info=info)
  5141. compute_utils.notify_about_volume_attach_detach(
  5142. context, instance, self.host,
  5143. action=fields.NotificationAction.VOLUME_ATTACH,
  5144. phase=fields.NotificationPhase.END,
  5145. volume_id=bdm.volume_id)
  5146. def _notify_volume_usage_detach(self, context, instance, bdm):
  5147. if CONF.volume_usage_poll_interval <= 0:
  5148. return
  5149. mp = bdm.device_name
  5150. # Handle bootable volumes which will not contain /dev/
  5151. if '/dev/' in mp:
  5152. mp = mp[5:]
  5153. try:
  5154. vol_stats = self.driver.block_stats(instance, mp)
  5155. if vol_stats is None:
  5156. return
  5157. except NotImplementedError:
  5158. return
  5159. LOG.debug("Updating volume usage cache with totals", instance=instance)
  5160. rd_req, rd_bytes, wr_req, wr_bytes, flush_ops = vol_stats
  5161. vol_usage = objects.VolumeUsage(context)
  5162. vol_usage.volume_id = bdm.volume_id
  5163. vol_usage.instance_uuid = instance.uuid
  5164. vol_usage.project_id = instance.project_id
  5165. vol_usage.user_id = instance.user_id
  5166. vol_usage.availability_zone = instance.availability_zone
  5167. vol_usage.curr_reads = rd_req
  5168. vol_usage.curr_read_bytes = rd_bytes
  5169. vol_usage.curr_writes = wr_req
  5170. vol_usage.curr_write_bytes = wr_bytes
  5171. vol_usage.save(update_totals=True)
  5172. self.notifier.info(context, 'volume.usage',
  5173. compute_utils.usage_volume_info(vol_usage))
  5174. def _detach_volume(self, context, bdm, instance, destroy_bdm=True,
  5175. attachment_id=None):
  5176. """Detach a volume from an instance.
  5177. :param context: security context
  5178. :param bdm: nova.objects.BlockDeviceMapping volume bdm to detach
  5179. :param instance: the Instance object to detach the volume from
  5180. :param destroy_bdm: if True, the corresponding BDM entry will be marked
  5181. as deleted. Disabling this is useful for operations
  5182. like rebuild, when we don't want to destroy BDM
  5183. :param attachment_id: The volume attachment_id for the given instance
  5184. and volume.
  5185. """
  5186. volume_id = bdm.volume_id
  5187. compute_utils.notify_about_volume_attach_detach(
  5188. context, instance, self.host,
  5189. action=fields.NotificationAction.VOLUME_DETACH,
  5190. phase=fields.NotificationPhase.START,
  5191. volume_id=volume_id)
  5192. self._notify_volume_usage_detach(context, instance, bdm)
  5193. LOG.info('Detaching volume %(volume_id)s',
  5194. {'volume_id': volume_id}, instance=instance)
  5195. driver_bdm = driver_block_device.convert_volume(bdm)
  5196. driver_bdm.detach(context, instance, self.volume_api, self.driver,
  5197. attachment_id=attachment_id, destroy_bdm=destroy_bdm)
  5198. info = dict(volume_id=volume_id)
  5199. self._notify_about_instance_usage(
  5200. context, instance, "volume.detach", extra_usage_info=info)
  5201. compute_utils.notify_about_volume_attach_detach(
  5202. context, instance, self.host,
  5203. action=fields.NotificationAction.VOLUME_DETACH,
  5204. phase=fields.NotificationPhase.END,
  5205. volume_id=volume_id)
  5206. if 'tag' in bdm and bdm.tag:
  5207. self._delete_disk_metadata(instance, bdm)
  5208. if destroy_bdm:
  5209. bdm.destroy()
  5210. def _delete_disk_metadata(self, instance, bdm):
  5211. for device in instance.device_metadata.devices:
  5212. if isinstance(device, objects.DiskMetadata):
  5213. if 'serial' in device:
  5214. if device.serial == bdm.volume_id:
  5215. instance.device_metadata.devices.remove(device)
  5216. instance.save()
  5217. break
  5218. else:
  5219. # NOTE(artom) We log the entire device object because all
  5220. # fields are nullable and may not be set
  5221. LOG.warning('Unable to determine whether to clean up '
  5222. 'device metadata for disk %s', device,
  5223. instance=instance)
  5224. @wrap_exception()
  5225. @wrap_instance_event(prefix='compute')
  5226. @wrap_instance_fault
  5227. def detach_volume(self, context, volume_id, instance, attachment_id):
  5228. """Detach a volume from an instance.
  5229. :param context: security context
  5230. :param volume_id: the volume id
  5231. :param instance: the Instance object to detach the volume from
  5232. :param attachment_id: The volume attachment_id for the given instance
  5233. and volume.
  5234. """
  5235. @utils.synchronized(instance.uuid)
  5236. def do_detach_volume(context, volume_id, instance, attachment_id):
  5237. bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
  5238. context, volume_id, instance.uuid)
  5239. self._detach_volume(context, bdm, instance,
  5240. attachment_id=attachment_id)
  5241. do_detach_volume(context, volume_id, instance, attachment_id)
  5242. def _init_volume_connection(self, context, new_volume,
  5243. old_volume_id, connector, bdm,
  5244. new_attachment_id, mountpoint):
  5245. new_volume_id = new_volume['id']
  5246. if new_attachment_id is None:
  5247. # We're dealing with an old-style attachment so initialize the
  5248. # connection so we can get the connection_info.
  5249. new_cinfo = self.volume_api.initialize_connection(context,
  5250. new_volume_id,
  5251. connector)
  5252. else:
  5253. # Check for multiattach on the new volume and if True, check to
  5254. # see if the virt driver supports multiattach.
  5255. # TODO(mriedem): This is copied from DriverVolumeBlockDevice
  5256. # and should be consolidated into some common code at some point.
  5257. vol_multiattach = new_volume.get('multiattach', False)
  5258. virt_multiattach = self.driver.capabilities.get(
  5259. 'supports_multiattach', False)
  5260. if vol_multiattach and not virt_multiattach:
  5261. raise exception.MultiattachNotSupportedByVirtDriver(
  5262. volume_id=new_volume_id)
  5263. # This is a new style attachment and the API created the new
  5264. # volume attachment and passed the id to the compute over RPC.
  5265. # At this point we need to update the new volume attachment with
  5266. # the host connector, which will give us back the new attachment
  5267. # connection_info.
  5268. new_cinfo = self.volume_api.attachment_update(
  5269. context, new_attachment_id, connector,
  5270. mountpoint)['connection_info']
  5271. if vol_multiattach:
  5272. # This will be used by the volume driver to determine the
  5273. # proper disk configuration.
  5274. new_cinfo['multiattach'] = True
  5275. old_cinfo = jsonutils.loads(bdm['connection_info'])
  5276. if old_cinfo and 'serial' not in old_cinfo:
  5277. old_cinfo['serial'] = old_volume_id
  5278. # NOTE(lyarwood): serial is not always present in the returned
  5279. # connection_info so set it if it is missing as we do in
  5280. # DriverVolumeBlockDevice.attach().
  5281. if 'serial' not in new_cinfo:
  5282. new_cinfo['serial'] = new_volume_id
  5283. return (old_cinfo, new_cinfo)
  5284. def _swap_volume(self, context, instance, bdm, connector,
  5285. old_volume_id, new_volume, resize_to,
  5286. new_attachment_id, is_cinder_migration):
  5287. new_volume_id = new_volume['id']
  5288. mountpoint = bdm['device_name']
  5289. failed = False
  5290. new_cinfo = None
  5291. try:
  5292. old_cinfo, new_cinfo = self._init_volume_connection(
  5293. context, new_volume, old_volume_id, connector,
  5294. bdm, new_attachment_id, mountpoint)
  5295. # NOTE(lyarwood): The Libvirt driver, the only virt driver
  5296. # currently implementing swap_volume, will modify the contents of
  5297. # new_cinfo when connect_volume is called. This is then saved to
  5298. # the BDM in swap_volume for future use outside of this flow.
  5299. msg = ("swap_volume: Calling driver volume swap with "
  5300. "connection infos: new: %(new_cinfo)s; "
  5301. "old: %(old_cinfo)s" %
  5302. {'new_cinfo': new_cinfo, 'old_cinfo': old_cinfo})
  5303. # Both new and old info might contain password
  5304. LOG.debug(strutils.mask_password(msg), instance=instance)
  5305. self.driver.swap_volume(context, old_cinfo, new_cinfo, instance,
  5306. mountpoint, resize_to)
  5307. if new_attachment_id:
  5308. self.volume_api.attachment_complete(context, new_attachment_id)
  5309. msg = ("swap_volume: Driver volume swap returned, new "
  5310. "connection_info is now : %(new_cinfo)s" %
  5311. {'new_cinfo': new_cinfo})
  5312. LOG.debug(strutils.mask_password(msg))
  5313. except Exception as ex:
  5314. failed = True
  5315. with excutils.save_and_reraise_exception():
  5316. tb = traceback.format_exc()
  5317. compute_utils.notify_about_volume_swap(
  5318. context, instance, self.host,
  5319. fields.NotificationPhase.ERROR,
  5320. old_volume_id, new_volume_id, ex, tb)
  5321. if new_cinfo:
  5322. msg = ("Failed to swap volume %(old_volume_id)s "
  5323. "for %(new_volume_id)s")
  5324. LOG.exception(msg, {'old_volume_id': old_volume_id,
  5325. 'new_volume_id': new_volume_id},
  5326. instance=instance)
  5327. else:
  5328. msg = ("Failed to connect to volume %(volume_id)s "
  5329. "with volume at %(mountpoint)s")
  5330. LOG.exception(msg, {'volume_id': new_volume_id,
  5331. 'mountpoint': bdm['device_name']},
  5332. instance=instance)
  5333. # The API marked the volume as 'detaching' for the old volume
  5334. # so we need to roll that back so the volume goes back to
  5335. # 'in-use' state.
  5336. self.volume_api.roll_detaching(context, old_volume_id)
  5337. if new_attachment_id is None:
  5338. # The API reserved the new volume so it would be in
  5339. # 'attaching' status, so we need to unreserve it so it
  5340. # goes back to 'available' status.
  5341. self.volume_api.unreserve_volume(context, new_volume_id)
  5342. else:
  5343. # This is a new style attachment for the new volume, which
  5344. # was created in the API. We just need to delete it here
  5345. # to put the new volume back into 'available' status.
  5346. self.volume_api.attachment_delete(
  5347. context, new_attachment_id)
  5348. finally:
  5349. # TODO(mriedem): This finally block is terribly confusing and is
  5350. # trying to do too much. We should consider removing the finally
  5351. # block and move whatever needs to happen on success and failure
  5352. # into the blocks above for clarity, even if it means a bit of
  5353. # redundant code.
  5354. conn_volume = new_volume_id if failed else old_volume_id
  5355. if new_cinfo:
  5356. LOG.debug("swap_volume: removing Cinder connection "
  5357. "for volume %(volume)s", {'volume': conn_volume},
  5358. instance=instance)
  5359. if bdm.attachment_id is None:
  5360. # This is the pre-3.44 flow for new-style volume
  5361. # attachments so just terminate the connection.
  5362. self.volume_api.terminate_connection(context,
  5363. conn_volume,
  5364. connector)
  5365. else:
  5366. # This is a new style volume attachment. If we failed, then
  5367. # the new attachment was already deleted above in the
  5368. # exception block and we have nothing more to do here. If
  5369. # swap_volume was successful in the driver, then we need to
  5370. # "detach" the original attachment by deleting it.
  5371. if not failed:
  5372. self.volume_api.attachment_delete(
  5373. context, bdm.attachment_id)
  5374. # Need to make some decisions based on whether this was
  5375. # a Cinder initiated migration or not. The callback to
  5376. # migration completion isn't needed in the case of a
  5377. # nova initiated simple swap of two volume
  5378. # "volume-update" call so skip that. The new attachment
  5379. # scenarios will give us a new attachment record and
  5380. # that's what we want.
  5381. if bdm.attachment_id and not is_cinder_migration:
  5382. # we don't callback to cinder
  5383. comp_ret = {'save_volume_id': new_volume_id}
  5384. else:
  5385. # NOTE(lyarwood): The following call to
  5386. # os-migrate-volume-completion returns a dict containing
  5387. # save_volume_id, this volume id has two possible values :
  5388. # 1. old_volume_id if we are migrating (retyping) volumes
  5389. # 2. new_volume_id if we are swapping between two existing
  5390. # volumes
  5391. # This volume id is later used to update the volume_id and
  5392. # connection_info['serial'] of the BDM.
  5393. comp_ret = self.volume_api.migrate_volume_completion(
  5394. context,
  5395. old_volume_id,
  5396. new_volume_id,
  5397. error=failed)
  5398. LOG.debug("swap_volume: Cinder migrate_volume_completion "
  5399. "returned: %(comp_ret)s", {'comp_ret': comp_ret},
  5400. instance=instance)
  5401. return (comp_ret, new_cinfo)
  5402. @wrap_exception()
  5403. @wrap_instance_event(prefix='compute')
  5404. @wrap_instance_fault
  5405. def swap_volume(self, context, old_volume_id, new_volume_id, instance,
  5406. new_attachment_id):
  5407. """Swap volume for an instance."""
  5408. context = context.elevated()
  5409. compute_utils.notify_about_volume_swap(
  5410. context, instance, self.host,
  5411. fields.NotificationPhase.START,
  5412. old_volume_id, new_volume_id)
  5413. bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
  5414. context, old_volume_id, instance.uuid)
  5415. connector = self.driver.get_volume_connector(instance)
  5416. resize_to = 0
  5417. old_volume = self.volume_api.get(context, old_volume_id)
  5418. # Yes this is a tightly-coupled state check of what's going on inside
  5419. # cinder, but we need this while we still support old (v1/v2) and
  5420. # new style attachments (v3.44). Once we drop support for old style
  5421. # attachments we could think about cleaning up the cinder-initiated
  5422. # swap volume API flows.
  5423. is_cinder_migration = False
  5424. if 'migration_status' in old_volume:
  5425. is_cinder_migration = old_volume['migration_status'] == 'migrating'
  5426. old_vol_size = old_volume['size']
  5427. new_volume = self.volume_api.get(context, new_volume_id)
  5428. new_vol_size = new_volume['size']
  5429. if new_vol_size > old_vol_size:
  5430. resize_to = new_vol_size
  5431. LOG.info('Swapping volume %(old_volume)s for %(new_volume)s',
  5432. {'old_volume': old_volume_id, 'new_volume': new_volume_id},
  5433. instance=instance)
  5434. comp_ret, new_cinfo = self._swap_volume(context,
  5435. instance,
  5436. bdm,
  5437. connector,
  5438. old_volume_id,
  5439. new_volume,
  5440. resize_to,
  5441. new_attachment_id,
  5442. is_cinder_migration)
  5443. # NOTE(lyarwood): Update the BDM with the modified new_cinfo and
  5444. # correct volume_id returned by Cinder.
  5445. save_volume_id = comp_ret['save_volume_id']
  5446. new_cinfo['serial'] = save_volume_id
  5447. values = {
  5448. 'connection_info': jsonutils.dumps(new_cinfo),
  5449. 'source_type': 'volume',
  5450. 'destination_type': 'volume',
  5451. 'snapshot_id': None,
  5452. 'volume_id': save_volume_id,
  5453. 'no_device': None}
  5454. if resize_to:
  5455. values['volume_size'] = resize_to
  5456. if new_attachment_id is not None:
  5457. # This was a volume swap for a new-style attachment so we
  5458. # need to update the BDM attachment_id for the new attachment.
  5459. values['attachment_id'] = new_attachment_id
  5460. LOG.debug("swap_volume: Updating volume %(volume_id)s BDM record with "
  5461. "%(updates)s", {'volume_id': bdm.volume_id,
  5462. 'updates': values},
  5463. instance=instance)
  5464. bdm.update(values)
  5465. bdm.save()
  5466. compute_utils.notify_about_volume_swap(
  5467. context, instance, self.host,
  5468. fields.NotificationPhase.END,
  5469. old_volume_id, new_volume_id)
  5470. @wrap_exception()
  5471. def remove_volume_connection(self, context, volume_id, instance):
  5472. """Remove the volume connection on this host
  5473. Detach the volume from this instance on this host, and if this is
  5474. the cinder v2 flow, call cinder to terminate the connection.
  5475. """
  5476. try:
  5477. bdm = objects.BlockDeviceMapping.get_by_volume_and_instance(
  5478. context, volume_id, instance.uuid)
  5479. driver_bdm = driver_block_device.convert_volume(bdm)
  5480. driver_bdm.driver_detach(context, instance,
  5481. self.volume_api, self.driver)
  5482. if bdm.attachment_id is None:
  5483. # cinder v2 api flow
  5484. connector = self.driver.get_volume_connector(instance)
  5485. self.volume_api.terminate_connection(context, volume_id,
  5486. connector)
  5487. except exception.NotFound:
  5488. pass
  5489. @wrap_exception()
  5490. @wrap_instance_event(prefix='compute')
  5491. @wrap_instance_fault
  5492. def attach_interface(self, context, instance, network_id, port_id,
  5493. requested_ip, tag):
  5494. """Use hotplug to add an network adapter to an instance."""
  5495. if not self.driver.capabilities.get('supports_attach_interface',
  5496. False):
  5497. raise exception.AttachInterfaceNotSupported(
  5498. instance_uuid=instance.uuid)
  5499. if (tag and not
  5500. self.driver.capabilities.get('supports_tagged_attach_interface',
  5501. False)):
  5502. raise exception.NetworkInterfaceTaggedAttachNotSupported()
  5503. compute_utils.notify_about_instance_action(
  5504. context, instance, self.host,
  5505. action=fields.NotificationAction.INTERFACE_ATTACH,
  5506. phase=fields.NotificationPhase.START)
  5507. bind_host_id = self.driver.network_binding_host_id(context, instance)
  5508. network_info = self.network_api.allocate_port_for_instance(
  5509. context, instance, port_id, network_id, requested_ip,
  5510. bind_host_id=bind_host_id, tag=tag)
  5511. if len(network_info) != 1:
  5512. LOG.error('allocate_port_for_instance returned %(ports)s '
  5513. 'ports', {'ports': len(network_info)})
  5514. # TODO(elod.illes): an instance.interface_attach.error notification
  5515. # should be sent here
  5516. raise exception.InterfaceAttachFailed(
  5517. instance_uuid=instance.uuid)
  5518. image_meta = objects.ImageMeta.from_instance(instance)
  5519. try:
  5520. self.driver.attach_interface(context, instance, image_meta,
  5521. network_info[0])
  5522. except exception.NovaException as ex:
  5523. port_id = network_info[0].get('id')
  5524. LOG.warning("attach interface failed , try to deallocate "
  5525. "port %(port_id)s, reason: %(msg)s",
  5526. {'port_id': port_id, 'msg': ex},
  5527. instance=instance)
  5528. try:
  5529. self.network_api.deallocate_port_for_instance(
  5530. context, instance, port_id)
  5531. except Exception:
  5532. LOG.warning("deallocate port %(port_id)s failed",
  5533. {'port_id': port_id}, instance=instance)
  5534. tb = traceback.format_exc()
  5535. compute_utils.notify_about_instance_action(
  5536. context, instance, self.host,
  5537. action=fields.NotificationAction.INTERFACE_ATTACH,
  5538. phase=fields.NotificationPhase.ERROR,
  5539. exception=ex, tb=tb)
  5540. raise exception.InterfaceAttachFailed(
  5541. instance_uuid=instance.uuid)
  5542. compute_utils.notify_about_instance_action(
  5543. context, instance, self.host,
  5544. action=fields.NotificationAction.INTERFACE_ATTACH,
  5545. phase=fields.NotificationPhase.END)
  5546. return network_info[0]
  5547. @wrap_exception()
  5548. @wrap_instance_event(prefix='compute')
  5549. @wrap_instance_fault
  5550. def detach_interface(self, context, instance, port_id):
  5551. """Detach a network adapter from an instance."""
  5552. network_info = instance.info_cache.network_info
  5553. condemned = None
  5554. for vif in network_info:
  5555. if vif['id'] == port_id:
  5556. condemned = vif
  5557. break
  5558. if condemned is None:
  5559. raise exception.PortNotFound(_("Port %s is not "
  5560. "attached") % port_id)
  5561. compute_utils.notify_about_instance_action(
  5562. context, instance, self.host,
  5563. action=fields.NotificationAction.INTERFACE_DETACH,
  5564. phase=fields.NotificationPhase.START)
  5565. try:
  5566. self.driver.detach_interface(context, instance, condemned)
  5567. except exception.NovaException as ex:
  5568. # If the instance was deleted before the interface was detached,
  5569. # just log it at debug.
  5570. log_level = (logging.DEBUG
  5571. if isinstance(ex, exception.InstanceNotFound)
  5572. else logging.WARNING)
  5573. LOG.log(log_level,
  5574. "Detach interface failed, port_id=%(port_id)s, reason: "
  5575. "%(msg)s", {'port_id': port_id, 'msg': ex},
  5576. instance=instance)
  5577. raise exception.InterfaceDetachFailed(instance_uuid=instance.uuid)
  5578. else:
  5579. try:
  5580. self.network_api.deallocate_port_for_instance(
  5581. context, instance, port_id)
  5582. except Exception as ex:
  5583. with excutils.save_and_reraise_exception():
  5584. # Since this is a cast operation, log the failure for
  5585. # triage.
  5586. LOG.warning('Failed to deallocate port %(port_id)s '
  5587. 'for instance. Error: %(error)s',
  5588. {'port_id': port_id, 'error': ex},
  5589. instance=instance)
  5590. compute_utils.notify_about_instance_action(
  5591. context, instance, self.host,
  5592. action=fields.NotificationAction.INTERFACE_DETACH,
  5593. phase=fields.NotificationPhase.END)
  5594. def _get_compute_info(self, context, host):
  5595. return objects.ComputeNode.get_first_node_by_host_for_old_compat(
  5596. context, host)
  5597. @wrap_exception()
  5598. def check_instance_shared_storage(self, ctxt, instance, data):
  5599. """Check if the instance files are shared
  5600. :param ctxt: security context
  5601. :param instance: dict of instance data
  5602. :param data: result of driver.check_instance_shared_storage_local
  5603. Returns True if instance disks located on shared storage and
  5604. False otherwise.
  5605. """
  5606. return self.driver.check_instance_shared_storage_remote(ctxt, data)
  5607. @wrap_exception()
  5608. @wrap_instance_event(prefix='compute')
  5609. @wrap_instance_fault
  5610. def check_can_live_migrate_destination(self, ctxt, instance,
  5611. block_migration, disk_over_commit):
  5612. """Check if it is possible to execute live migration.
  5613. This runs checks on the destination host, and then calls
  5614. back to the source host to check the results.
  5615. :param context: security context
  5616. :param instance: dict of instance data
  5617. :param block_migration: if true, prepare for block migration
  5618. if None, calculate it in driver
  5619. :param disk_over_commit: if true, allow disk over commit
  5620. if None, ignore disk usage checking
  5621. :returns: a dict containing migration info
  5622. """
  5623. src_compute_info = obj_base.obj_to_primitive(
  5624. self._get_compute_info(ctxt, instance.host))
  5625. dst_compute_info = obj_base.obj_to_primitive(
  5626. self._get_compute_info(ctxt, CONF.host))
  5627. dest_check_data = self.driver.check_can_live_migrate_destination(ctxt,
  5628. instance, src_compute_info, dst_compute_info,
  5629. block_migration, disk_over_commit)
  5630. LOG.debug('destination check data is %s', dest_check_data)
  5631. try:
  5632. migrate_data = self.compute_rpcapi.\
  5633. check_can_live_migrate_source(ctxt, instance,
  5634. dest_check_data)
  5635. finally:
  5636. self.driver.cleanup_live_migration_destination_check(ctxt,
  5637. dest_check_data)
  5638. return migrate_data
  5639. @wrap_exception()
  5640. @wrap_instance_event(prefix='compute')
  5641. @wrap_instance_fault
  5642. def check_can_live_migrate_source(self, ctxt, instance, dest_check_data):
  5643. """Check if it is possible to execute live migration.
  5644. This checks if the live migration can succeed, based on the
  5645. results from check_can_live_migrate_destination.
  5646. :param ctxt: security context
  5647. :param instance: dict of instance data
  5648. :param dest_check_data: result of check_can_live_migrate_destination
  5649. :returns: a dict containing migration info
  5650. """
  5651. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  5652. ctxt, instance.uuid)
  5653. is_volume_backed = compute_utils.is_volume_backed_instance(
  5654. ctxt, instance, bdms)
  5655. dest_check_data.is_volume_backed = is_volume_backed
  5656. block_device_info = self._get_instance_block_device_info(
  5657. ctxt, instance, refresh_conn_info=False, bdms=bdms)
  5658. result = self.driver.check_can_live_migrate_source(ctxt, instance,
  5659. dest_check_data,
  5660. block_device_info)
  5661. LOG.debug('source check data is %s', result)
  5662. return result
  5663. @wrap_exception()
  5664. @wrap_instance_event(prefix='compute')
  5665. @wrap_instance_fault
  5666. def pre_live_migration(self, context, instance, block_migration, disk,
  5667. migrate_data):
  5668. """Preparations for live migration at dest host.
  5669. :param context: security context
  5670. :param instance: dict of instance data
  5671. :param block_migration: if true, prepare for block migration
  5672. :param disk: disk info of instance
  5673. :param migrate_data: A dict or LiveMigrateData object holding data
  5674. required for live migration without shared
  5675. storage.
  5676. :returns: migrate_data containing additional migration info
  5677. """
  5678. LOG.debug('pre_live_migration data is %s', migrate_data)
  5679. migrate_data.old_vol_attachment_ids = {}
  5680. bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  5681. context, instance.uuid)
  5682. network_info = self.network_api.get_instance_nw_info(context, instance)
  5683. self._notify_about_instance_usage(
  5684. context, instance, "live_migration.pre.start",
  5685. network_info=network_info)
  5686. compute_utils.notify_about_instance_action(
  5687. context, instance, self.host,
  5688. action=fields.NotificationAction.LIVE_MIGRATION_PRE,
  5689. phase=fields.NotificationPhase.START, bdms=bdms)
  5690. connector = self.driver.get_volume_connector(instance)
  5691. try:
  5692. for bdm in bdms:
  5693. if bdm.is_volume and bdm.attachment_id is not None:
  5694. # This bdm uses the new cinder v3.44 API.
  5695. # We will create a new attachment for this
  5696. # volume on this migration destination host. The old
  5697. # attachment will be deleted on the source host
  5698. # when the migration succeeds. The old attachment_id
  5699. # is stored in dict with the key being the bdm.volume_id
  5700. # so it can be restored on rollback.
  5701. #
  5702. # Also note that attachment_update is not needed as we
  5703. # are providing the connector in the create call.
  5704. attach_ref = self.volume_api.attachment_create(
  5705. context, bdm.volume_id, bdm.instance_uuid,
  5706. connector=connector, mountpoint=bdm.device_name)
  5707. # save current attachment so we can detach it on success,
  5708. # or restore it on a rollback.
  5709. # NOTE(mdbooth): This data is no longer used by the source
  5710. # host since change I0390c9ff. We can't remove it until we
  5711. # are sure the source host has been upgraded.
  5712. migrate_data.old_vol_attachment_ids[bdm.volume_id] = \
  5713. bdm.attachment_id
  5714. # update the bdm with the new attachment_id.
  5715. bdm.attachment_id = attach_ref['id']
  5716. bdm.save()
  5717. block_device_info = self._get_instance_block_device_info(
  5718. context, instance, refresh_conn_info=True,
  5719. bdms=bdms)
  5720. # The driver pre_live_migration will plug vifs on the host. We call
  5721. # plug_vifs before calling ensure_filtering_rules_for_instance, to
  5722. # ensure bridge is set up.
  5723. migrate_data = self.driver.pre_live_migration(context,
  5724. instance,
  5725. block_device_info,
  5726. network_info,
  5727. disk,
  5728. migrate_data)
  5729. LOG.debug('driver pre_live_migration data is %s', migrate_data)
  5730. # driver.pre_live_migration is what plugs vifs on the destination
  5731. # host so now we can set the wait_for_vif_plugged flag in the
  5732. # migrate_data object which the source compute will use to
  5733. # determine if it should wait for a 'network-vif-plugged' event
  5734. # from neutron before starting the actual guest transfer in the
  5735. # hypervisor
  5736. migrate_data.wait_for_vif_plugged = (
  5737. CONF.compute.live_migration_wait_for_vif_plug)
  5738. # NOTE(tr3buchet): setup networks on destination host
  5739. self.network_api.setup_networks_on_host(context, instance,
  5740. self.host)
  5741. # Creating filters to hypervisors and firewalls.
  5742. # An example is that nova-instance-instance-xxx,
  5743. # which is written to libvirt.xml(Check "virsh nwfilter-list")
  5744. # This nwfilter is necessary on the destination host.
  5745. # In addition, this method is creating filtering rule
  5746. # onto destination host.
  5747. self.driver.ensure_filtering_rules_for_instance(instance,
  5748. network_info)
  5749. except Exception:
  5750. # If we raise, migrate_data with the updated attachment ids
  5751. # will not be returned to the source host for rollback.
  5752. # So we need to rollback new attachments here.
  5753. with excutils.save_and_reraise_exception():
  5754. old_attachments = migrate_data.old_vol_attachment_ids
  5755. for bdm in bdms:
  5756. if (bdm.is_volume and bdm.attachment_id is not None and
  5757. bdm.volume_id in old_attachments):
  5758. self.volume_api.attachment_delete(context,
  5759. bdm.attachment_id)
  5760. bdm.attachment_id = old_attachments[bdm.volume_id]
  5761. bdm.save()
  5762. # Volume connections are complete, tell cinder that all the
  5763. # attachments have completed.
  5764. for bdm in bdms:
  5765. if bdm.is_volume and bdm.attachment_id is not None:
  5766. self.volume_api.attachment_complete(context,
  5767. bdm.attachment_id)
  5768. self._notify_about_instance_usage(
  5769. context, instance, "live_migration.pre.end",
  5770. network_info=network_info)
  5771. compute_utils.notify_about_instance_action(
  5772. context, instance, self.host,
  5773. action=fields.NotificationAction.LIVE_MIGRATION_PRE,
  5774. phase=fields.NotificationPhase.END, bdms=bdms)
  5775. LOG.debug('pre_live_migration result data is %s', migrate_data)
  5776. return migrate_data
  5777. @staticmethod
  5778. def _neutron_failed_migration_callback(event_name, instance):
  5779. msg = ('Neutron reported failure during migration '
  5780. 'with %(event)s for instance %(uuid)s')
  5781. msg_args = {'event': event_name, 'uuid': instance.uuid}
  5782. if CONF.vif_plugging_is_fatal:
  5783. raise exception.VirtualInterfacePlugException(msg % msg_args)
  5784. LOG.error(msg, msg_args)
  5785. @staticmethod
  5786. def _get_neutron_events_for_live_migration(instance):
  5787. # We don't generate events if CONF.vif_plugging_timeout=0
  5788. # meaning that the operator disabled using them.
  5789. if CONF.vif_plugging_timeout and utils.is_neutron():
  5790. return [('network-vif-plugged', vif['id'])
  5791. for vif in instance.get_network_info()]
  5792. else:
  5793. return []
  5794. def _cleanup_pre_live_migration(self, context, dest, instance,
  5795. migration, migrate_data, source_bdms):
  5796. """Helper method for when pre_live_migration fails
  5797. Sets the migration status to "error" and rolls back the live migration
  5798. setup on the destination host.
  5799. :param context: The user request context.
  5800. :type context: nova.context.RequestContext
  5801. :param dest: The live migration destination hostname.
  5802. :type dest: str
  5803. :param instance: The instance being live migrated.
  5804. :type instance: nova.objects.Instance
  5805. :param migration: The migration record tracking this live migration.
  5806. :type migration: nova.objects.Migration
  5807. :param migrate_data: Data about the live migration, populated from
  5808. the destination host.
  5809. :type migrate_data: Subclass of nova.objects.LiveMigrateData
  5810. :param source_bdms: BDMs prior to modification by the destination
  5811. compute host. Set by _do_live_migration and not
  5812. part of the callback interface, so this is never
  5813. None
  5814. """
  5815. self._set_migration_status(migration, 'error')
  5816. # Make sure we set this for _rollback_live_migration()
  5817. # so it can find it, as expected if it was called later
  5818. migrate_data.migration = migration
  5819. self._rollback_live_migration(context, instance, dest,
  5820. migrate_data=migrate_data,
  5821. source_bdms=source_bdms)
  5822. def _do_live_migration(self, context, dest, instance, block_migration,
  5823. migration, migrate_data):
  5824. # NOTE(danms): We should enhance the RT to account for migrations
  5825. # and use the status field to denote when the accounting has been
  5826. # done on source/destination. For now, this is just here for status
  5827. # reporting
  5828. self._set_migration_status(migration, 'preparing')
  5829. source_bdms = objects.BlockDeviceMappingList.get_by_instance_uuid(
  5830. context, instance.uuid)
  5831. class _BreakWaitForInstanceEvent(Exception):
  5832. """Used as a signal to stop waiting for the network-vif-plugged
  5833. event when we discover that
  5834. [compute]/live_migration_wait_for_vif_plug is not set on the
  5835. destination.
  5836. """
  5837. pass
  5838. events = self._get_neutron_events_for_live_migration(instance)
  5839. try:
  5840. if ('block_migration' in migrate_data and
  5841. migrate_data.block_migration):
  5842. block_device_info = self._get_instance_block_device_info(
  5843. context, instance, bdms=source_bdms)
  5844. disk = self.driver.get_instance_disk_info(
  5845. instance, block_device_info=block_device_info)
  5846. else:
  5847. disk = None
  5848. deadline = CONF.vif_plugging_timeout
  5849. error_cb = self._neutron_failed_migration_callback
  5850. # In order to avoid a race with the vif plugging that the virt
  5851. # driver does on the destination host, we register our events
  5852. # to wait for before calling pre_live_migration. Then if the
  5853. # dest host reports back that we shouldn't wait, we can break
  5854. # out of the context manager using _BreakWaitForInstanceEvent.
  5855. with self.virtapi.wait_for_instance_event(
  5856. instance, events, deadline=deadline,
  5857. error_callback=error_cb):
  5858. with timeutils.StopWatch() as timer:
  5859. migrate_data = self.compute_rpcapi.pre_live_migration(
  5860. context, instance,
  5861. block_migration, disk, dest, migrate_data)
  5862. LOG.info('Took %0.2f seconds for pre_live_migration on '
  5863. 'destination host %s.',
  5864. timer.elapsed(), dest, instance=instance)
  5865. wait_for_vif_plugged = (
  5866. 'wait_for_vif_plugged' in migrate_data and
  5867. migrate_data.wait_for_vif_plugged)
  5868. if events and not wait_for_vif_plugged:
  5869. raise _BreakWaitForInstanceEvent
  5870. except _BreakWaitForInstanceEvent:
  5871. if events:
  5872. LOG.debug('Not waiting for events after pre_live_migration: '
  5873. '%s. ', events, instance=instance)
  5874. # This is a bit weird, but we need to clear sys.exc_info() so that
  5875. # oslo.log formatting does not inadvertently use it later if an
  5876. # error message is logged without an explicit exc_info. This is
  5877. # only a problem with python 2.
  5878. if six.PY2:
  5879. sys.exc_clear()
  5880. except exception.VirtualInterfacePlugException:
  5881. with excutils.save_and_reraise_exception():
  5882. LOG.exception('Failed waiting for network virtual interfaces '
  5883. 'to be plugged on the destination host %s.',
  5884. dest, instance=instance)
  5885. self._cleanup_pre_live_migration(
  5886. context, dest, instance, migration, migrate_data,
  5887. source_bdms)
  5888. except eventlet.timeout.Timeout:
  5889. msg = 'Timed out waiting for events: %s'
  5890. LOG.warning(msg, events, instance=instance)
  5891. if CONF.vif_plugging_is_fatal:
  5892. self._cleanup_pre_live_migration(
  5893. context, dest, instance, migration, migrate_data,
  5894. source_bdms)
  5895. raise exception.MigrationError(reason=msg % events)
  5896. except Exception:
  5897. with excutils.save_and_reraise_exception():
  5898. LOG.exception('Pre live migration failed at %s',
  5899. dest, instance=instance)
  5900. self._cleanup_pre_live_migration(
  5901. context, dest, instance, migration, migrate_data,
  5902. source_bdms)
  5903. # NOTE(Kevin_Zheng): Pop the migration from the waiting queue
  5904. # if it exist in the queue, then we are good to moving on, if
  5905. # not, some other process must have aborted it, then we should
  5906. # rollback.
  5907. try:
  5908. self._waiting_live_migrations.pop(instance.uuid)
  5909. except KeyError:
  5910. LOG.debug('Migration %s aborted by another process, rollback.',
  5911. migration.uuid, instance=instance)
  5912. migrate_data.migration = migration
  5913. self._rollback_live_migration(context, instance, dest,
  5914. migrate_data, 'cancelled',
  5915. source_bdms=source_bdms)
  5916. self._notify_live_migrate_abort_end(context, instance)
  5917. return
  5918. self._set_migration_status(migration, 'running')
  5919. if migrate_data:
  5920. migrate_data.migration = migration
  5921. # NOTE(mdbooth): pre_live_migration will update connection_info and
  5922. # attachment_id on all volume BDMS to reflect the new destination
  5923. # host attachment. We fetch BDMs before that to retain connection_info
  5924. # and attachment_id relating to the source host for post migration
  5925. # cleanup.
  5926. post_live_migration = functools.partial(self._post_live_migration,
  5927. source_bdms=source_bdms)
  5928. rollback_live_migration = functools.partial(
  5929. self._rollback_live_migration, source_bdms=source_bdms)
  5930. LOG.debug('live_migration data is %s', migrate_data)
  5931. try:
  5932. self.driver.live_migration(context, instance, dest,
  5933. post_live_migration,
  5934. rollback_live_migration,
  5935. block_migration, migrate_data)
  5936. except Exception:
  5937. LOG.exception('Live migration failed.', instance=instance)
  5938. with excutils.save_and_reraise_exception():
  5939. # Put instance and migration into error state,
  5940. # as its almost certainly too late to rollback
  5941. self._set_migration_status(migration, 'error')
  5942. # first refresh instance as it may have got updated by
  5943. # post_live_migration_at_destination
  5944. instance.refresh()
  5945. self._set_instance_obj_error_state(context, instance,
  5946. clean_task_state=True)
  5947. @wrap_exception()
  5948. @wrap_instance_event(prefix='compute')
  5949. @wrap_instance_fault
  5950. def live_migration(self, context, dest, instance, block_migration,
  5951. migration, migrate_data):
  5952. """Executing live migration.
  5953. :param context: security context
  5954. :param dest: destination host
  5955. :param instance: a nova.objects.instance.Instance object
  5956. :param block_migration: if true, prepare for block migration
  5957. :param migration: an nova.objects.Migration object
  5958. :param migrate_data: implementation specific params
  5959. """
  5960. self._set_migration_status(migration, 'queued')
  5961. # NOTE(Kevin_Zheng): Submit the live_migration job to the pool and
  5962. # put the returned Future object into dict mapped with migration.uuid
  5963. # in order to be able to track and abort it in the future.
  5964. self._waiting_live_migrations[instance.uuid] = (None, None)
  5965. try:
  5966. future = self._live_migration_executor.submit(
  5967. self._do_live_migration, context, dest, instance,
  5968. block_migration, migration, migrate_data)
  5969. self._waiting_live_migrations[instance.uuid] = (migration, future)
  5970. except RuntimeError:
  5971. # ThreadPoolExecutor.submit will raise RuntimeError if the pool
  5972. # is shutdown, which happens in _cleanup_live_migrations_in_pool.
  5973. LOG.info('Migration %s failed to submit as the compute service '
  5974. 'is shutting down.', migration.uuid, instance=instance)
  5975. self._set_migration_status(migration, 'error')
  5976. raise exception.LiveMigrationNotSubmitted(
  5977. migration_uuid=migration.uuid, instance_uuid=instance.uuid)
  5978. @wrap_exception()
  5979. @wrap_instance_event(prefix='compute')
  5980. @wrap_instance_fault
  5981. def live_migration_force_complete(self, context, instance):
  5982. """Force live migration to complete.
  5983. :param context: Security context
  5984. :param instance: The instance that is being migrated
  5985. """
  5986. self._notify_about_instance_usage(
  5987. context, instance, 'live.migration.force.complete.start')
  5988. compute_utils.notify_about_instance_action(
  5989. context, instance, self.host,
  5990. action=fields.NotificationAction.LIVE_MIGRATION_FORCE_COMPLETE,
  5991. phase=fields.NotificationPhase.START)
  5992. self.driver.live_migration_force_complete(instance)
  5993. self._notify_about_instance_usage(
  5994. context, instance, 'live.migration.force.complete.end')
  5995. compute_utils.notify_about_instance_action(
  5996. context, instance, self.host,
  5997. action=fields.NotificationAction.LIVE_MIGRATION_FORCE_COMPLETE,
  5998. phase=fields.NotificationPhase.END)
  5999. def _notify_live_migrate_abort_end(self, context, instance):
  6000. self._notify_about_instance_usage(
  6001. context, instance, 'live.migration.abort.end')
  6002. compute_utils.notify_about_instance_action(
  6003. context, instance, self.host,
  6004. action=fields.NotificationAction.LIVE_MIGRATION_ABORT,
  6005. phase=fields.NotificationPhase.END)
  6006. @wrap_exception()
  6007. @wrap_instance_event(prefix='compute')
  6008. @wrap_instance_fault
  6009. def live_migration_abort(self, context, instance, migration_id):
  6010. """Abort an in-progress live migration.
  6011. :param context: Security context
  6012. :param instance: The instance that is being migrated
  6013. :param migration_id: ID of in-progress live migration
  6014. """
  6015. self._notify_about_instance_usage(
  6016. context, instance, 'live.migration.abort.start')
  6017. compute_utils.notify_about_instance_action(
  6018. context, instance, self.host,
  6019. action=fields.NotificationAction.LIVE_MIGRATION_ABORT,
  6020. phase=fields.NotificationPhase.START)
  6021. # NOTE(Kevin_Zheng): Pop the migration out from the queue, this might
  6022. # lead to 3 scenarios:
  6023. # 1. The selected migration is still in queue, and the future.cancel()
  6024. # succeed, then the abort action is succeed, mark the migration
  6025. # status to 'cancelled'.
  6026. # 2. The selected migration is still in queue, but the future.cancel()
  6027. # failed, then the _do_live_migration() has started executing, and
  6028. # the migration status is 'preparing', then we just pop it from the
  6029. # queue, and the migration process will handle it later. And the
  6030. # migration status couldn't be 'running' in this scenario because
  6031. # if _do_live_migration has started executing and we've already
  6032. # popped it from the queue and set the migration status to
  6033. # 'running' at this point, popping it here will raise KeyError at
  6034. # which point we check if it's running and if so, we abort the old
  6035. # way.
  6036. # 3. The selected migration is not in the queue, then the migration
  6037. # status is 'running', let the driver handle it.
  6038. try:
  6039. migration, future = (
  6040. self._waiting_live_migrations.pop(instance.uuid))
  6041. if future and future.cancel():
  6042. # If we got here, we've successfully aborted the queued
  6043. # migration and _do_live_migration won't run so we need
  6044. # to set the migration status to cancelled and send the
  6045. # notification. If Future.cancel() fails, it means
  6046. # _do_live_migration is running and the migration status
  6047. # is preparing, and _do_live_migration() itself will attempt
  6048. # to pop the queued migration, hit a KeyError, and rollback,
  6049. # set the migration to cancelled and send the
  6050. # live.migration.abort.end notification.
  6051. self._set_migration_status(migration, 'cancelled')
  6052. except KeyError:
  6053. migration = objects.Migration.get_by_id(context, migration_id)
  6054. if migration.status != 'running':
  6055. raise exception.InvalidMigrationState(
  6056. migration_id=migration_id, instance_uuid=instance.uuid,
  6057. state=migration.status, method='abort live migration')
  6058. self.driver.live_migration_abort(instance)
  6059. self._notify_live_migrate_abort_end(context, instance)
  6060. def _live_migration_cleanup_flags(self, migrate_data):
  6061. """Determine whether disks or instance path need to be cleaned up after
  6062. live migration (at source on success, at destination on rollback)
  6063. Block migration needs empty image at destination host before migration
  6064. starts, so if any failure occurs, any empty images has to be deleted.
  6065. Also Volume backed live migration w/o shared storage needs to delete
  6066. newly created instance-xxx dir on the destination as a part of its
  6067. rollback process
  6068. :param migrate_data: implementation specific data
  6069. :returns: (bool, bool) -- do_cleanup, destroy_disks
  6070. """
  6071. # NOTE(pkoniszewski): block migration specific params are set inside
  6072. # migrate_data objects for drivers that expose block live migration
  6073. # information (i.e. Libvirt, Xenapi and HyperV). For other drivers
  6074. # cleanup is not needed.
  6075. do_cleanup = False
  6076. destroy_disks = False
  6077. if isinstance(migrate_data, migrate_data_obj.LibvirtLiveMigrateData):
  6078. # No instance booting at source host, but instance dir
  6079. # must be deleted for preparing next block migration
  6080. # must be deleted for preparing next live migration w/o shared
  6081. # storage
  6082. do_cleanup = not migrate_data.is_shared_instance_path
  6083. destroy_disks = not migrate_data.is_shared_block_storage
  6084. elif isinstance(migrate_data, migrate_data_obj.XenapiLiveMigrateData):
  6085. do_cleanup = migrate_data.block_migration
  6086. destroy_disks = migrate_data.block_migration
  6087. elif isinstance(migrate_data, migrate_data_obj.HyperVLiveMigrateData):
  6088. # NOTE(claudiub): We need to cleanup any zombie Planned VM.
  6089. do_cleanup = True
  6090. destroy_disks = not migrate_data.is_shared_instance_path
  6091. return (do_cleanup, destroy_disks)
  6092. @wrap_exception()
  6093. @wrap_instance_fault
  6094. def _post_live_migration(self, ctxt, instance, dest,
  6095. block_migration=False, migrate_data=None,
  6096. source_bdms=None):
  6097. """Post operations for live migration.
  6098. This method is called from live_migration
  6099. and mainly updating database record.
  6100. :param ctxt: security context
  6101. :param instance: instance dict
  6102. :param dest: destination host
  6103. :param block_migration: if true, prepare for block migration
  6104. :param migrate_data: if not None, it is a dict which has data
  6105. :param source_bdms: BDMs prior to modification by the destination
  6106. compute host. Set by _do_live_migration and not
  6107. part of the callback interface, so this is never
  6108. None
  6109. required for live migration without shared storage
  6110. """
  6111. LOG.info('_post_live_migration() is started..',
  6112. instance=instance)
  6113. # Cleanup source host post live-migration
  6114. block_device_info = self._get_instance_block_device_info(
  6115. ctxt, instance, bdms=source_bdms)
  6116. self.driver.post_live_migration(ctxt, instance, block_device_info,
  6117. migrate_data)
  6118. # Detaching volumes.
  6119. connector = self.driver.get_volume_connector(instance)
  6120. for bdm in source_bdms:
  6121. if bdm.is_volume:
  6122. # Detaching volumes is a call to an external API that can fail.
  6123. # If it does, we need to handle it gracefully so that the call
  6124. # to post_live_migration_at_destination - where we set instance
  6125. # host and task state - still happens. We need to rethink the
  6126. # current approach of setting instance host and task state
  6127. # AFTER a whole bunch of things that could fail in unhandled
  6128. # ways, but that is left as a TODO(artom).
  6129. try:
  6130. if bdm.attachment_id is None:
  6131. # Prior to cinder v3.44:
  6132. # We don't want to actually mark the volume detached,
  6133. # or delete the bdm, just remove the connection from
  6134. # this host.
  6135. #
  6136. # remove the volume connection without detaching from
  6137. # hypervisor because the instance is not running
  6138. # anymore on the current host
  6139. self.volume_api.terminate_connection(ctxt,
  6140. bdm.volume_id,
  6141. connector)
  6142. else:
  6143. # cinder v3.44 api flow - delete the old attachment
  6144. # for the source host
  6145. self.volume_api.attachment_delete(ctxt,
  6146. bdm.attachment_id)
  6147. except Exception as e:
  6148. if bdm.attachment_id is None:
  6149. LOG.error('Connection for volume %s not terminated on '
  6150. 'source host %s during post_live_migration: '
  6151. '%s', bdm.volume_id, self.host,
  6152. six.text_type(e), instance=instance)
  6153. else:
  6154. LOG.error('Volume attachment %s not deleted on source '
  6155. 'host %s during post_live_migration: %s',
  6156. bdm.attachment_id, self.host,
  6157. six.text_type(e), instance=instance)
  6158. # Releasing vlan.
  6159. # (not necessary in current implementation?)
  6160. network_info = self.network_api.get_instance_nw_info(ctxt, instance)
  6161. self._notify_about_instance_usage(ctxt, instance,
  6162. "live_migration._post.start",
  6163. network_info=network_info)
  6164. compute_utils.notify_about_instance_action(
  6165. ctxt, instance, self.host,
  6166. action=fields.NotificationAction.LIVE_MIGRATION_POST,
  6167. phase=fields.NotificationPhase.START)
  6168. # Releasing security group ingress rule.
  6169. LOG.debug('Calling driver.unfilter_instance from _post_live_migration',
  6170. instance=instance)
  6171. self.driver.unfilter_instance(instance,
  6172. network_info)
  6173. migration = {'source_compute': self.host,
  6174. 'dest_compute': dest, }
  6175. # For neutron, migrate_instance_start will activate the destination
  6176. # host port bindings, if there are any created by conductor before live
  6177. # migration started.
  6178. self.network_api.migrate_instance_start(ctxt,
  6179. instance,
  6180. migration)
  6181. destroy_vifs = False
  6182. try:
  6183. # It's possible that the vif type changed on the destination
  6184. # host and is already bound and active, so we need to use the
  6185. # stashed source vifs in migrate_data.vifs (if present) to unplug
  6186. # on the source host.
  6187. unplug_nw_info = network_info
  6188. if migrate_data and 'vifs' in migrate_data:
  6189. nw_info = []
  6190. for migrate_vif in migrate_data.vifs:
  6191. nw_info.append(migrate_vif.source_vif)
  6192. unplug_nw_info = network_model.NetworkInfo.hydrate(nw_info)
  6193. LOG.debug('Calling driver.post_live_migration_at_source '
  6194. 'with original source VIFs from migrate_data: %s',
  6195. unplug_nw_info, instance=instance)
  6196. self.driver.post_live_migration_at_source(ctxt, instance,
  6197. unplug_nw_info)
  6198. except NotImplementedError as ex:
  6199. LOG.debug(ex, instance=instance)
  6200. # For all hypervisors other than libvirt, there is a possibility
  6201. # they are unplugging networks from source node in the cleanup
  6202. # method
  6203. destroy_vifs = True
  6204. # NOTE(danms): Save source node before calling post method on
  6205. # destination, which will update it
  6206. source_node = instance.node
  6207. # Define domain at destination host, without doing it,
  6208. # pause/suspend/terminate do not work.
  6209. post_at_dest_success = True
  6210. try:
  6211. self.compute_rpcapi.post_live_migration_at_destination(ctxt,
  6212. instance, block_migration, dest)
  6213. except Exception as error:
  6214. post_at_dest_success = False
  6215. # We don't want to break _post_live_migration() if
  6216. # post_live_migration_at_destination() fails as it should never
  6217. # affect cleaning up source node.
  6218. LOG.exception("Post live migration at destination %s failed",
  6219. dest, instance=instance, error=error)
  6220. do_cleanup, destroy_disks = self._live_migration_cleanup_flags(
  6221. migrate_data)
  6222. if do_cleanup:
  6223. LOG.debug('Calling driver.cleanup from _post_live_migration',
  6224. instance=instance)
  6225. self.driver.