# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
"""
Driver for Solaris Zones (nee Containers):
"""
import base64
import glob
import os
import platform
import shutil
import tempfile
import uuid
default=None,
default=None,
'live migration. If not specified, a common encryption '
'algorithm will be negotiated. Options include: none or '
'the name of a supported OpenSSL cipher algorithm.'),
'Glance image service.'),
'metadata.'),
]
# These should match the strings returned by the zone_state_str()
# function in the (private) libzonecfg library. These values are in turn
# returned in the 'state' string of the Solaris Zones' RAD interface by
# the zonemgr(3RAD) provider.
# Mapping between zone state and Nova power_state.
}
# Solaris Zones brands as defined in brands(5).
# Mapping between supported zone brands and the name of the corresponding
# brand template.
ZONE_BRAND_SOLARIS: 'SYSdefault',
ZONE_BRAND_SOLARIS_KZ: 'SYSsolaris-kz',
}
# Required in order to create a zone VNC console SMF service instance
# The underlying Solaris Zones framework does not expose a specific
# version number, instead relying on feature tests to identify what is
# and what is not supported. A HYPERVISOR_VERSION is defined here for
# Nova's use but it generally should not be changed unless there is a
# incompatible change such as concerning kernel zone live migration.
KSTAT_TYPE = {
'NVVT_STR': 'string',
'NVVT_STRS': 'strings',
'NVVT_INT': 'integer',
'NVVT_INTS': 'integers',
'NVVT_KSTAT': 'kstat',
}
"""Lookup specified resource from specified Solaris Zone."""
try:
return None
except Exception:
raise
"""Lookup specified property from specified Solaris Zone resource."""
try:
[prop])
return None
except Exception:
raise
"""Lookup specified property with value from specified Solaris Zone
resource. Returns resource object if matching value is found, else None
"""
try:
return resource
else:
return None
return None
except Exception:
raise
"""Format the payload from a zonemgr(3RAD) rad.client.ObjectError
exception into a sensible error string that can be logged. Newlines
are converted to a colon-space string to create a single line.
If the exception was something other than rad.client.ObjectError,
just return it as a string.
"""
return result
"not align on %(align)s boundary.")
""" Extending the volume api to support additional cinder sub-commands
"""
availability_zone=None, source_volume=None):
"""Clone the source volume by calling the cinderclient version of
create with a source_volid argument
:param context: the context for the clone
:param size: size of the new volume, must be the same as the source
volume
:param name: display_name of the new volume
:param description: display_description of the new volume
:param snapshot: Snapshot object
:param image_id: image_id to create the volume from
:param volume_type: type of volume
:param metadata: Additional metadata for the volume
:param availability_zone: zone:host where the volume is to be created
:param source_volume: Volume object
Returns a volume object
"""
if snapshot is not None:
else:
snapshot_id = None
if source_volume is not None:
else:
source_volid = None
else:
try:
except cinder_exception.OverLimit:
except (cinder_exception.BadRequest,
"""Update the fields of a volume for example used to rename a volume
via a call to cinderclient
:param context: the context for the update
:param volume_id: the id of the volume to update
"""
"""Extend the size of a cinder volume by calling the cinderclient
:param context: the context for the extend
:param volume: the volume object to extend
:param newsize: the new size of the volume in GB
"""
"""ZoneConfig - context manager for access zone configurations.
Automatically opens the configuration for a zone and commits any changes
before exiting
"""
"""zone is a zonemgr object representing either a kernel zone or
non-global zone.
"""
"""enables the editing of the zone."""
try:
return self
"via zonemgr(3RAD): %s")
raise
"""looks for any kind of exception before exiting. If one is found,
cancel any configuration changes and reraise the exception. If not,
commit the new configuration.
"""
# We received some kind of exception. Cancel the config and raise.
raise
else:
# commit the config
try:
"instance '%s' via zonemgr(3RAD): %s")
# Last ditch effort to cleanup.
raise
"""sets a property for an existing resource OR creates a new resource
with the given property(s).
"""
# the value is already set
return
try:
if current is None:
else:
"instance '%s' via zonemgr(3RAD): %s")
raise
"""creates a new resource with an optional property list, or set the
property if the resource exists and ignore_exists is true.
:param ignore_exists: If the resource exists, set the property for the
resource.
"""
if props is None:
props = []
try:
if (ignore_exists and
return
"'%s' via zonemgr(3RAD): %s")
raise
"""removes resources whose properties include the optional property
list specified in props.
"""
if props is None:
props = []
try:
"via zonemgr(3RAD): %s")
raise
"""Clear property values of a given resource
"""
try:
"for instance '%s' via zonemgr(3RAD): %s")
raise
"""Solaris Zones Driver using the zonemgr(3RAD) and kstat(3RAD) providers.
The interface to this class talks in terms of 'instances' (Amazon EC2 and
internal Nova terminology), by which we mean 'running virtual machine'
(XenAPI terminology) or domain (Xen or libvirt terminology).
An instance has an ID, which is the identifier chosen by Nova to represent
the instance further up the stack. This is unfortunately also called a
'name' elsewhere. As far as this layer is concerned, 'instance ID' and
'instance name' are synonyms.
Note that the instance ID or name is not human-readable or
customer-controlled -- it's an internal ID chosen by Nova. At the
nova.virt layer, instances do not have human-readable names at all -- such
things are only known higher up the stack.
Most virtualization platforms will also have their own identity schemes,
to uniquely identify a VM or domain. These IDs must stay internal to the
platform-specific layer, and never escape the connection interface. The
platform-specific layer is responsible for keeping track of which instance
ID maps to which platform-specific ID, and vice versa.
Some methods here take an instance of nova.compute.service.Instance. This
is the data structure used by nova.compute to store details regarding an
instance, and pass them into this layer. This layer is responsible for
translating that generic data structure into terms that are specific to the
virtualization platform.
"""
capabilities = {
"has_imagecache": False,
"supports_recreate": True,
"supports_migrate_to_same_host": False
}
self._archive_manager = None
self._compute_event_callback = None
self._host_stats = {}
self._initiator = None
self._install_engine = None
self._kstat_control = None
self._rad_connection = None
self._zone_manager = None
if self._rad_connection is None:
else:
# taken from rad.connect.RadConnection.__repr__ to look for a
# closed connection
# the RAD connection has been lost. Reconnect to RAD
return self._rad_connection
try:
if (self._zone_manager is None or
return self._zone_manager
try:
if (self._kstat_control is None or
return self._kstat_control
try:
if (self._archive_manager is None or
return self._archive_manager
"""Initialize anything that is necessary for the driver to function,
including catching up with currently running VM's on the given host.
"""
# TODO(Vek): Need to pass context in for access to auth_token
pass
"""Clean up anything that is necessary for the driver gracefully stop,
including ending remote sessions. This is optional.
"""
pass
"""Get Fibre Channel HBA information."""
out = None
try:
except processutils.ProcessExecutionError:
return []
if out is None:
raise RuntimeError(_("Cannot find any Fibre Channel HBAs"))
hbas = []
hba = {}
# Collect the following hba-port data:
# 1: Port WWN
# 2: State (online|offline)
# 3: Node WWN
# New HBA port entry
hba = {}
continue
# Skip Target mode ports
if mode != 'Initiator':
break
continue
continue
hba = {}
"""Get Fibre Channel WWNNs from the system, if any."""
wwnns = []
return wwnns
"""Get Fibre Channel WWPNs from the system, if any."""
wwpns = []
return wwpns
""" Return the iSCSI initiator node name IQN for this host """
try:
'initiator-node')
# Sample first line of command output:
# Initiator node name: iqn.1986-03.com.sun:01:e00000000000.4f757217
return initiator_iqn
return None
"""Return a Solaris Zones object via RAD by name."""
try:
return None
except Exception:
raise
return zone
"""Return the running state, one of the power_state codes."""
"""Convert a number of pages of memory into a total size in KBytes."""
"""Return the maximum memory in KBytes allowed."""
mem_resource = 'swap'
else:
mem_resource = 'physical'
if max_mem is not None:
# If physical property in capped-memory doesn't exist, this may
# represent a non-global zone so just return the system's total
# memory.
"""Return the memory in KBytes used by the domain."""
# There isn't any way of determining this from the hypervisor
# perspective in Solaris, so just return the _get_max_mem() value
# for now.
"""Return the number of virtual CPUs for the domain.
In the case of kernel zones, the number of virtual CPUs a zone
ends up with depends on whether or not there were 'virtual-cpu'
or 'dedicated-cpu' resources in the configuration or whether
there was an assigned pool in the configuration. This algorithm
attempts to emulate what the virtual platform code does to
determine a number of virtual CPUs to use.
"""
# If a 'virtual-cpu' resource exists, use the minimum number of
# CPUs defined there.
if ncpus is not None:
# Otherwise if a 'dedicated-cpu' resource exists, use the maximum
# number of CPUs defined there.
if ncpus is not None:
# Finally if neither resource exists but the zone was assigned a
# pool in the configuration, the number of CPUs would be the size
# of the processor set. Currently there's no way of easily
# determining this so use the system's notion of the total number
# of online CPUs.
"""Return Kstat snapshot data via RAD as a dictionary."""
try:
return None
ks_data = {}
return ks_data
total = 0
try:
except TypeError:
return None
return total
try:
except TypeError:
value = None
return value
"""Return the CPU time used in nanoseconds."""
return 0
# The retry value of 3 was determined by the "we shouldn't hit this
# often, but if we do it should resolve quickly so try again"+1
# algorithm.
total = 0
return total
"keeps changing"))
return 0
"""Get the current status of an instance, by name (not ID!)
:param instance: nova.objects.instance.Instance object
Returns a InstanceInfo object
"""
# TODO(Vek): Need to pass context in for access to auth_token
if zone is None:
"""Return the total number of virtual machines.
Return the number of virtual machines that the hypervisor knows
about.
.. note::
This implementation works for all drivers, but it is
not particularly efficient. Maintainers of the virt drivers are
encouraged to override this method with something more
efficient.
"""
"""Checks existence of an instance on the host.
:param instance: The instance to lookup
Returns True if an instance with the supplied ID exists on
the host, False otherwise.
.. note::
This implementation works for all drivers, but it is
not particularly efficient. Maintainers of the virt drivers are
encouraged to override this method with something more
efficient.
"""
try:
except NotImplementedError:
"""Estimate the virtualization overhead required to build an instance
of the given flavor.
Defaults to zero, drivers should override if per-instance overhead
calculations are desired.
:returns: Dict of estimated overhead values.
"""
return {'memory_mb': 0}
"""Return a list of all Solaris Zones objects via RAD."""
"""Return the names of all the instances known to the virtualization
layer, as a list.
"""
# TODO(Vek): Need to pass context in for access to auth_token
instances_list = []
return instances_list
"""Return the UUIDS of all the instances known to the virtualization
layer, as a list.
"""
raise NotImplementedError()
root_ci = None
if entry['connection_info'] is None:
continue
# Let's make sure this is a well formed connection_info, by
# checking if it has a serial key that represents the
# volume_id. If not check to see if the block device has a
# volume_id, if so then assign this to the root_ci.serial.
#
# If we cannot repair the connection_info then simply do not
# return a root_ci and let the caller decide if they want to
# fail or not.
else:
"the connection info for the root device "
root_ci = None
continue
if not recreate:
msg = (_("Unable to find the root device for instance '%s'.")
% instance['name'])
return root_ci
"""Attempt to get the hostid from the current configured zone and
return the hostid. Otherwise return None, and do not set the hostid in
the instance
"""
if hostid is not None:
return hostid
if zone is None:
return None
if hostid:
return hostid
attach_block_devices, network_info=None,
"""Destroy and re-make this instance.
A 'rebuild' effectively purges all existing data from the system and
remakes the VM with given 'metadata' and 'personalities'.
This base class method shuts down the VM, detaches all block devices,
then spins up the new VM afterwards. It may be overridden by
hypervisors that need to - e.g. for optimisations, or when the 'VM'
is actually proxied and needs to be held across the shutdown + spin
up steps.
:param context: security context
:param instance: nova.objects.instance.Instance
This function should use the data there to guide
the creation of the new instance.
:param nova.objects.ImageMeta image_meta:
The metadata of the image of the instance.
:param injected_files: User files to inject into instance.
:param admin_password: Administrator password to set in instance.
:param bdms: block-device-mappings to use for rebuild
:param detach_block_devices: function to detach block devices. See
nova.compute.manager.ComputeManager:_rebuild_default_impl for
usage.
:param attach_block_devices: function to attach block devices. See
nova.compute.manager.ComputeManager:_rebuild_default_impl for
usage.
:param network_info:
:py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
:param recreate: True if the instance is being recreated on a new
hypervisor - all the cleanup of old state is skipped.
:param block_device_info: Information about block devices to be
attached to the instance.
:param preserve_ephemeral: True if the default ephemeral storage
partition must be preserved on rebuild
"""
if recreate:
if brand == ZONE_BRAND_SOLARIS:
msg = (_("'%s' branded zones do not currently support "
"evacuation.") % brand)
else:
if recreate:
if root_ci is not None:
else:
driver_type = 'local'
if driver_type not in shared_storage:
msg = (_("Root device is not on shared storage for instance "
if not recreate:
if root_ci is not None:
# Go ahead and remove the root bdm from the bdms so that we do
# not trip up spawn either checking against the use of c1d0 or
# attempting to re-attach the root device.
if rootdevname is not None:
break
# Instead of using a boolean for 'rebuilding' scratch data, use a
# string because the object will translate it to a string anyways.
if recreate:
else:
if zone is None:
if recreate:
if (entry['connection_info'] is None or
continue
if admin_password is not None:
# Because there is no way to make sure a zone is ready upon
# returning from a boot request. We must give the zone a few
# seconds to boot before attempting to set the admin password.
"""Retrieve the flavor object as specified in the instance object"""
instance['instance_type_id'])
"""Fetch an image using Glance given the instance's image_ref."""
% iref)
return image
try:
# touch the empty .downloading file
pass
instance['project_id'])
return image
raise
"""Validate a glance image for compatibility with the instance."""
# Skip if the image was already checked and confirmed as valid.
return
try:
else:
# Validate the image at this point to ensure:
# - contains one deployable system
reason = _("Image must contain only a single deployable system.")
# - matching architecture
reason = (_("Unified Archive architecture '%s' is incompatible "
"with this compute host's architecture, '%s'.")
% (deployable_arch, compute_arch))
# For some reason we have gotten the wrong architecture image,
# which should have been filtered by the scheduler. One reason this
# could happen is because the images architecture type is
# incorrectly set. Check for this and report a better reason.
glanceapi = glance_api()
"on the Glance image."))
# - single root pool only
reason = _("Image contains more than one ZFS pool.")
# - looks like it's OK
"""Validate the flavor for compatibility with zone brands"""
if brand == ZONE_BRAND_SOLARIS_KZ:
# verify the memory is 256mb aligned
# non-zero result so it doesn't align
raise MemoryAlignmentIncorrect(
align='256')
"""Returns a suri(5) formatted string based on connection_info.
Currently supports local ZFS volume, NFS, Fibre Channel and iSCSI
driver types.
"""
if driver_type == 'local':
elif driver_type == 'iscsi':
# suri(5) format:
# iscsi://<host>[:<port>]/target.<IQN>,lun.<LUN>
# luname-only URI format for the multipathing:
# iscsi://<host>[:<port>]/luname.naa.<ID>
# Sample iSCSI connection data values:
# target_portal: 192.168.1.244:3260
# target_iqn: iqn.2010-10.org.openstack:volume-a89c.....
# target_lun: 1
suri = None
if 'target_iqns' in data:
try:
'-vS', target)
'-t', 'iscsi',
if "luname.naa." in line:
"LUN '%s' is '%s'.") %
(target_lun, line))
if suri is None:
data['target_iqn'],
data['target_lun'])
# TODO(npower): need to handle CHAP authentication also
elif driver_type == 'nfs':
suri = (
'nfs://cinder:cinder@%s/%s' %
)
elif driver_type == 'fibre_channel':
# Ensure there's a fibre channel HBA.
if not hbas:
"no Fibre Channel HBA initiators were found"))
raise exception.InvalidVolume(
reason="No host Fibre Channel initiator found")
# If the volume was exported just a few seconds previously then
# it will probably not be visible to the local adapter yet.
# Invoke 'fcinfo remote-port' on all local HBA ports to trigger
# a refresh.
return suri
"""Searching the LU based URI for the FC LU. """
wwns = []
else:
try:
return line
else:
msg = _("Unable to lookup URI of Fibre Channel volume "
"with lun '%s'." % target_lun)
"""Set Solaris Zone's global properties if supplied via flavor."""
if zone is None:
# TODO(dcomay): Should figure this out via the brands themselves.
zonecfg_items = [
'bootargs',
'brand',
'hostid'
]
if brand == ZONE_BRAND_SOLARIS:
['file-mac-profile', 'fs-allowed', 'limitpriv'])
else:
# Ignore not-zonecfg-scoped brand properties.
continue
# Ignore the 'brand' property if present.
if prop == 'brand':
continue
# Ignore but warn about unsupported zonecfg-scoped properties.
if prop not in zonecfg_items:
"set on flavor for instance '%s'")
continue
"""Create a (Cinder) volume service backed boot volume"""
try:
"Boot volume for instance '%s' (%s)"
# creating a new volume, so we do likewise here.
while True:
return volume
raise
"""Connect a (Cinder) volume service backed boot volume"""
# Check connection_info to determine if the provided volume is
# local to this compute node. If it is, then don't use it for
# Solaris branded zones in order to avoid a known ZFS deadlock issue
# when using a zpool within another zpool on the same system.
if brand == ZONE_BRAND_SOLARIS:
if driver_type == 'local':
msg = _("Detected 'local' zvol driver volume type "
"from volume service, which should not be "
"used as a boot device for 'solaris' "
"branded zones.")
elif driver_type == 'iscsi':
# Check for a potential loopback iSCSI situation
# Strip off the port number (eg. 127.0.0.1:3260)
# Strip any enclosing '[' and ']' brackets for
# IPv6 addresses.
# Check if target_host is an IP or hostname matching the
# connector host or IP, which would mean the provisioned
# iSCSI LUN is on the same host as the instance.
msg = _("iSCSI connection info from volume "
"service indicates that the target is a "
"local volume, which should not be used "
"as a boot device for 'solaris' branded "
"zones.")
# Assuming that fibre_channel is non-local
elif driver_type != 'fibre_channel':
# Some other connection type that we don't understand
# Let zone use some local fallback instead.
msg = _("Unsupported volume driver type '%s' can not be used "
"as a boot device for zones." % driver_type)
# Volume looks OK to use. Notify Cinder of the attachment.
return connection_info
"""Set the boot device specified by connection_info"""
if zone is None:
# ZOSS device configuration is different for the solaris-kz brand
if brand == ZONE_BRAND_SOLARIS_KZ:
else:
"""Set number of VCPUs in a Solaris Zone configuration."""
if zone is None:
# The Solaris Zone brand type is used to specify the type of
# 'cpu' resource set in the Solaris Zone configuration.
if brand == ZONE_BRAND_SOLARIS:
vcpu_resource = 'capped-cpu'
else:
vcpu_resource = 'virtual-cpu'
# TODO(dcomay): Until 17881862 is resolved, this should be turned into
# an appropriate 'rctl' resource for the 'capped-cpu' case.
"""Set memory cap in a Solaris Zone configuration."""
if zone is None:
# The Solaris Zone brand type is used to specify the type of
# 'memory' cap set in the Solaris Zone configuration.
if brand == ZONE_BRAND_SOLARIS:
mem_resource = 'swap'
else:
mem_resource = 'physical'
'correctly configured. VM will not have network '
'connectivity') % vif)
'external-ids:iface-status=active',
]
try:
msg = (_("Failed to add port '%s' with MAC address '%s' to "
"OVS Bridge '%s': %s")
try:
(port, ovs_bridge))
msg = (_("Unable to remove port '%s' from the OVS "
if log_warnings:
else:
if not network_info:
return
# first find out all the anets for a given instance
try:
'-po', 'link,macaddress')
msg = (_("Unable to get interfaces for instance '%s': %s")
anetdict = {}
# we now have a list of VNICs that belong to the VM
# we need to map the VNIC to the bridge
for vif in network_info:
if anet is None:
'to instance %s')
instance['name']))
continue
# remove the anets from the OVS bridge
'list-ports', ovs_bridge]
try:
msg = (_("Unable to get interfaces for instance '%s': %s")
continue
# Need to be admin to retrieve provider:network_type attribute
lower_link = None
if network_type == 'vxlan':
lower_link = 'ovs.vxlan1'
# retrieve the other_config information from Open_vSwitch table
try:
raise
if not other_config:
msg = (_("'other_config' column in 'Open_vSwitch' OVSDB table "
"is not configured. Please configure it so that the "
"lower-link can be determined for the instance's "
"interface."))
if not bridge_mappings:
msg = (_("'bridge_mappings' info is not set in the "
"'other_config' column of 'Open_vSwitch' OVSDB "
"table. Please configure it so that the lower-link "
"can be determined for the instance's interface."))
if physical_network in bridge_mapping:
break
if not lower_link:
msg = (_("Failed to determine the lower_link for vif '%s'.") %
(vif))
else:
# TYPE_GRE and TYPE_LOCAL
if first_anet:
if mtu > 0:
else:
'false'),
if mtu > 0:
if brand == ZONE_BRAND_SOLARIS:
'linkname', prop_filter)
else:
return anetname
sc_dir):
"""add networking information to the zone."""
if zone is None:
if not network_info:
if brand == ZONE_BRAND_SOLARIS:
else:
return
dhcp_server = \
enable_dhcp = dhcp_server is not None
nameservers = []
vif)
# create the required sysconfig file (or skip if this is part of a
# resize or evacuate process)
task_states.REBUILD_SPAWNING] or \
if enable_dhcp:
else:
"""Use the instance name to specify the pathname for the suspend image.
"""
if zone is None:
'%{zonename}')
"""verify the SC profile(s) passed in contain an entry for
system/config-user to configure the root account. If an SSH key is
specified, configure root's profile to use it.
"""
encrypted_password = None
# encrypt admin password, using SHA-256 as default
if admin_password is not None:
# find all XML files in sc_dir
# look for config-user properties
# a service element was found for config-user. Verify
# root's password is set, the admin account name is set and
# the admin's password is set
# look for identity properties
# Verify all of the requirements were met. Create the required SMF
# profile(s) if needed.
if admin_password is not None and sshkey is not None:
# store password for horizon retrieval
if encrypted_password is not None or sshkey is not None:
# set up the root account as 'normal' with no expiration,
# an ssh key, and a root password
else:
# sets up root account with expiration if sshkey is None
# and password is none
elif sshkey is not None:
if hostname_needed and name is not None:
sc_dir, admin_password=None):
"""Create a new Solaris Zone configuration."""
# If unspecified, default zone brand is ZONE_BRAND_SOLARIS
if brand is None:
"flavor '%s'. Defaulting to 'solaris'"
% flavor['name']))
# TODO(dcomay): Detect capability via libv12n(3LIB) or virtinfo(1M).
if template is None:
msg = (_("Invalid brand '%s' specified for instance '%s'"
task_states.REBUILD_SPAWNING] or \
if sc_profile is not None:
try:
if hostid:
if connection_info is not None:
raise
"""Create a VNC console SMF service for a Solaris Zone"""
# Basic environment checks first: vncserver and xterm
"compute node. %s is missing. Run 'pkg install "
"x11/server/xvnc'") % VNC_SERVER_PATH)
"compute node. %s is missing. Run 'pkg install "
"terminal/xterm'") % XTERM_PATH)
# TODO(npower): investigate using RAD instead of CLI invocation
try:
"console SMF service for instance '%s'") % name)
return
raise
"""Delete a VNC console SMF service for a Solaris Zone"""
# TODO(npower): investigate using RAD instead of CLI invocation
try:
name)
"VNC console SMF service for instance '%s'")
% name)
return
"'%s': %s")
raise
"""Enable a zone VNC console SMF service"""
# TODO(npower): investigate using RAD instead of CLI invocation
try:
# The console SMF service exits with SMF_TEMP_DISABLE to prevent
# unnecessarily coming online at boot. Tell it to really bring
# it online.
'setprop', 'vnc/nova-enabled=true')
'refresh')
"VNC console SMF service for instance '%s'")
% name)
return
raise
# Allow some time for the console service to come online.
while True:
try:
if state == 'online':
break
"'%s' state. Run 'svcs -x %s' for details.")
# Wait for service state to transition to (hopefully) online
# state or offline/maintenance states.
raise
# TODO(npower): investigate using RAD instead of CLI invocation
try:
# The console SMF service exits with SMF_TEMP_DISABLE to prevent
# unnecessarily coming online at boot. Make that happen.
'setprop', 'vnc/nova-enabled=false')
'refresh')
"zone VNC console SMF service '%s': %s")
% (console_fmri, reason))
raise
"""Disable a zone VNC console SMF service"""
"console SMF service for instance '%s'") % name)
return
# TODO(npower): investigate using RAD instead of CLI invocation
try:
'-s', console_fmri)
# The console service sets a SMF instance property for the port
# on which the VNC service is listening. The service needs to be
# refreshed to reset the property value
try:
'refresh')
"""Returns state of the instance zone VNC console SMF service"""
"VNC console SMF service for instance '%s'")
% name)
return None
# TODO(npower): investigate using RAD instead of CLI invocation
try:
"console SMF service for instance '%s': %s")
raise
"""Returns True if the instance has a zone VNC console SMF service"""
# TODO(npower): investigate using RAD instead of CLI invocation
try:
return True
except Exception:
return False
"""Install a new Solaris Zone root file system."""
if zone is None:
# log the zone's configuration
# the directory isn't empty so pass it along to install
try:
raise
"""Power on a Solaris Zone."""
if zone is None:
# Attempt to update the zones hostid in the instance data, to catch
# those instances that might have been created without a hostid stored.
bootargs = []
persistent = 'False'
# Get any bootargs already set in the zone
# Get any bootargs set in the instance metadata by the user
if meta_bootargs:
persistent = str(
# Temporarily clear bootargs in zone config
try:
finally:
# We have consumed the metadata bootargs and
# the user asked for them not to be persistent so
# clear them out now.
if reset_bootargs:
# restore original boot args in zone config
"""Uninstall an existing Solaris Zone root file system."""
if zone is None:
return
try:
"instance '%s' via zonemgr(3RAD): %s")
raise
"""Delete an existing Solaris Zone configuration."""
try:
raise
Once this successfully completes, the instance should be
running (power_state.RUNNING).
If this fails, any partial instance should be completely
cleaned up, and the virtualization platform should be in the state
that it was before this call began.
:param context: security context
:param instance: nova.objects.instance.Instance
This function should use the data there to guide
the creation of the new instance.
:param nova.objects.ImageMeta image_meta:
The metadata of the image of the instance.
:param injected_files: User files to inject into instance.
:param admin_password: Administrator password to set in instance.
:param network_info:
:py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
:param block_device_info: Information about block devices to be
attached to the instance.
"""
# c1d0 is the standard dev for the default boot device.
# Irrelevant value for ZFS, but Cinder gets stroppy without it.
mountpoint = "c1d0"
# Ensure no block device mappings attempt to use the reserved boot
# device (c1d0).
if entry['connection_info'] is None:
continue
msg = (_("Unable to assign '%s' to block device as it is"
"reserved for the root file system") % mount_device)
# Attempt to provision a (Cinder) volume service backed boot volume
try:
# This Cinder volume is not usable for ZOSS so discard it.
# zonecfg will apply default zonepath dataset configuration
# instead. Carry on
connection_info = None
# Something really bad happened. Don't pass Go.
raise
# create a new directory for SC profiles
try:
if entry['connection_info'] is not None:
# At least attempt to uninstall the instance, depending on where
# the installation got to there could be things left behind that
# need to be cleaned up, e.g a root zpool etc.
try:
try:
if connection_info is not None:
raise
finally:
# remove the sc_profile temp directory
if connection_info is not None:
# there's only one bdm for this instance at this point
# update the required attributes
"""Power off a Solaris Zone."""
if zone is None:
# Attempt to update the zones hostid in the instance data, to catch
# those instances that might have been created without a hostid stored.
try:
if halt_type == 'SOFT':
else:
# 'HARD'
# A shutdown state could still be reached if the error was
# informational and ignorable.
"trying to power off instance '%s' via "
return
"""Reverts the zones configuration to pre-resize config
"""
if old_rvid:
"""Destroy the specified instance from the Hypervisor.
If the instance is not found (for example if networking failed), this
function should still succeed. It's probably a good idea to log a
warning in that case.
:param context: security context
:param instance: Instance object as returned by DB layer.
:param network_info:
:py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
:param block_device_info: Information about block devices that should
be detached from the instance.
:param destroy_disks: Indicates if disks should be destroyed
:param migrate_data: implementation specific params
"""
return
# A destroy is issued for the original zone for an evac case. If
# the evac fails we need to protect the zone from deletion when
# power comes back on.
return
try:
# These methods log if problems occur so no need to double log
# here. Just catch any stray exceptions and allow destroy to
# proceed.
except Exception:
pass
# If instance cannot be found, just return.
if zone is None:
% name)
return
try:
# One last point of house keeping. If we are deleting the instance
# during a resize operation we want to make sure the cinder volumes are
# properly cleaned up. We need to do this here, because the periodic
# task that comes along and cleans these things up isn't nice enough to
# pass a context in so that we could simply do the work there. But
# because we have access to a context, we can handle the work here and
# let the periodic task simply clean up the left over zone
# configuration that might be left around. Note that the left over
# zone will only show up in zoneadm list, not nova list.
#
# If the task state is RESIZE_REVERTING do not process these because
# the cinder volume cleanup is taken care of in
# finish_revert_migration.
return
if volid:
try:
except Exception:
pass
"""Cleanup the instance resources .
Instance should have been destroyed from the Hypervisor before calling
this method.
:param context: security context
:param instance: Instance object as returned by DB layer.
:param network_info:
:py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
:param block_device_info: Information about block devices that should
be detached from the instance.
:param destroy_disks: Indicates if disks should be destroyed
:param migrate_data: implementation specific params
"""
raise NotImplementedError()
block_device_info=None, bad_volumes_callback=None):
"""Reboot the specified instance.
After this is called successfully, the instance's state
goes back to power_state.RUNNING. The virtualization
platform should ensure that the reboot action has completed
:param instance: nova.objects.instance.Instance
:param network_info:
:py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
:param reboot_type: Either a HARD or SOFT reboot
:param block_device_info: Info pertaining to attached volumes
:param bad_volumes_callback: Function to handle any bad volumes
encountered
"""
if zone is None:
return
bootargs = []
persistent = 'False'
# Get any bootargs already set in the zone
# Get any bootargs set in the instance metadata by the user
if meta_bootargs:
persistent = str(
# Temporarily clear bootargs in zone config
try:
if reboot_type == 'SOFT':
else:
finally:
# We have consumed the metadata bootargs and
# the user asked for them not to be persistent so
# clear them out now.
if reset_bootargs:
# restore original boot args in zone config
# TODO(Vek): Need to pass context in for access to auth_token
raise NotImplementedError()
"""Builds a string containing the console output (capped at
MAX_CONSOLE_BYTES characters) by reassembling the log files
that Solaris Zones framework maintains for each zone.
"""
console_str = ""
# Examine the log files in most-recently modified order, keeping
# track of the size of each file and of how many characters have
# been seen. If there are still characters left to incorporate,
# then the contents of the log file in question are prepended to
# the console string built so far. When the number of characters
# available has run out, the last fragment under consideration
# will likely begin within the middle of a line. As such, the
# start of the fragment up to the next newline is thrown away.
# The remainder constitutes the start of the resulting console
# output which is then prepended to the console string built so
# far and the result returned.
if size == 0:
continue
if avail < 0:
break
fragment = ''
return console_str
"""Get console output for an instance
:param context: security context
:param instance: nova.objects.instance.Instance
"""
"""Get connection info for a vnc console.
:param context: security context
:param instance: nova.objects.instance.Instance
:returns an instance of console.type.ConsoleVNC
"""
# Do not provide console access prematurely. Zone console access is
# exclusive and zones that are still installing require their console.
# Grabbing the zone console will break installation.
"completed installation. Try again later.") % name)
"instance '%s'") % name)
# The console service sets an SMF instance property for the port
# on which the VNC service is listening. The service needs to be
# refreshed to reflect the current property value
# TODO(npower): investigate using RAD instead of CLI invocation
try:
'refresh')
raise
try:
internal_access_path=None)
"console SMF service '%s': %s"
% (console_fmri, reason)))
"""Get connection info for a spice console.
:param context: security context
:param instance: nova.objects.instance.Instance
:returns an instance of console.type.ConsoleSpice
"""
raise NotImplementedError()
"""Get connection info for a rdp console.
:param context: security context
:param instance: nova.objects.instance.Instance
:returns an instance of console.type.ConsoleRDP
"""
raise NotImplementedError()
"""Get connection info for a serial console.
:param context: security context
:param instance: nova.objects.instance.Instance
:returns an instance of console.type.ConsoleSerial
"""
raise NotImplementedError()
"""Get connection info for a MKS console.
:param context: security context
:param instance: nova.objects.instance.Instance
:returns an instance of console.type.ConsoleMKS
"""
raise NotImplementedError()
"""Return data about Solaris Zone diagnostics."""
return None
# Get the inital accumulated data kstat, then get the sys_zone kstat
# and sum all the "*_cur" statistics in it. Then re-get the accumulated
# kstat, and if the generation number hasn't changed, add its values.
# If it has changed, try again a few times then give up because
# something keeps pulling cpus out from under us.
# The list of cpu kstats in data must contain at least one element
# and all elements have the same map of statistics, since they're
# all the same kstat type. This gets a list of all the statistics
# which end in "_cur" from the first (guaranteed) kstat element.
k.endswith("_cur")]
# Remove the '_cur' from the statistic
break
else:
reason = (_("Could not get diagnostic info for instance '%s' "
# Remove any None valued elements from diagnostics and return it
return {k: v for k, v in diagnostics.items() if v is not None}
"""Return diagnostics data about the given instance.
:param nova.objects.instance.Instance instance:
The instance to which the diagnostic data should be returned.
:return: Has a big overlap to the return value of the newer interface
:func:`get_instance_diagnostics`
:rtype: dict
"""
# TODO(Vek): Need to pass context in for access to auth_token
if zone is None:
"""Return diagnostics data about the given instance.
:param nova.objects.instance.Instance instance:
The instance to which the diagnostic data should be returned.
:return: Has a big overlap to the return value of the older interface
:func:`get_diagnostics`
:rtype: nova.virt.diagnostics.Diagnostics
"""
raise NotImplementedError()
"""Return bandwidth usage counters for each interface on each
running VM.
:param instances: nova.objects.instance.InstanceList
"""
raise NotImplementedError()
"""Return usage info for volumes attached to vms on
a given host.-
"""
raise NotImplementedError()
"""Retrieves the IP address of the dom0
"""
# TODO(Vek): Need to pass context in for access to auth_token
"""Attach the disk to the instance at mountpoint using info."""
# TODO(npower): Apply mountpoint in a meaningful way to the zone
# For security reasons this is not permitted in a Solaris branded zone.
if zone is None:
if brand != ZONE_BRAND_SOLARIS_KZ:
# Only Solaris kernel zones are currently supported.
reason = (_("'%s' branded zones are not currently supported")
% brand)
raise NotImplementedError(reason)
if volume['bootable']:
# apply the configuration to the running zone
try:
raise
encryption=None):
"""Detach the disk attached to the instance."""
if zone is None:
if brand != ZONE_BRAND_SOLARIS_KZ:
# Only Solaris kernel zones are currently supported.
reason = (_("'%s' branded zones are not currently supported")
% brand)
raise NotImplementedError(reason)
# Check if the specific property value exists before attempting removal
suri)
if not resource:
return
# apply the configuration to the running zone
try:
except:
"to running instance '%s' because the "
"resource is most likely in use.")
# re-add the entry to the zone configuration so that the
# configuration will reflect what is in cinder before we raise
# the exception, therefore failing the detach and leaving the
# volume in-use.
raise
"""Replace the volume attached to the given `instance`.
:param dict old_connection_info:
The volume for this connection gets detached from the given
`instance`.
:param dict new_connection_info:
The volume for this connection gets attached to the given
'instance'.
:param nova.objects.instance.Instance instance:
The instance whose volume gets replaced by another one.
:param str mountpoint:
The mountpoint in the instance where the volume for
`old_connection_info` is attached to.
:param int resize_to:
If the new volume is larger than the old volume, it gets resized
to the given size (in Gigabyte) of `resize_to`.
:return: None
"""
raise NotImplementedError()
"""Use hotplug to add a network interface to a running instance.
The counter action to this is :func:`detach_interface`.
:param nova.objects.instance.Instance instance:
The instance which will get an additional network interface.
:param nova.objects.ImageMeta image_meta:
The metadata of the image of the instance.
:param nova.network.model.NetworkInfo vif:
The object which has the information about the interface to attach.
:raise nova.exception.NovaException: If the attach fails.
:return: None
"""
if zone is None:
# apply the configuration if the vm is ACTIVE
try:
msg = (_("Unable to attach interface to instance '%s' via "
vif['address'])]
# add port to ovs bridge
"""Use hotunplug to remove a network interface from a running instance.
The counter action to this is :func:`attach_interface`.
:param nova.objects.instance.Instance instance:
The instance which gets a network interface removed.
:param nova.network.model.NetworkInfo vif:
The object which has the information about the interface to detach.
:raise nova.exception.NovaException: If the detach fails.
:return: None
"""
if zone is None:
# Check if the specific property value exists before attempting removal
'mac-address',
vif['address'])
if not resource:
msg = (_("Interface with MAC address '%s' is not attached to "
break
break
vif['address'])])
# apply the configuration if the vm is ACTIVE
try:
except:
msg = (_("Unable to detach interface '%s' from running "
"instance '%s' because the resource is most likely "
"mac-address", "mtu"]
if brand == ZONE_BRAND_SOLARIS:
else:
# remove anet from OVS bridge
"""Make a best effort at cleaning up the volume that was created to
hold the new root disk
:param volume: new volume created by the call to cinder create
"""
try:
block_device_info=None,
"""Transfers the disk of a running instance in multiple phases, turning
off the instance before the end.
:param nova.objects.instance.Instance instance:
The instance whose disk should be migrated.
:param str dest:
The IP address of the destination host.
:param nova.objects.flavor.Flavor flavor:
The flavor of the instance whose disk get migrated.
:param nova.network.model.NetworkInfo network_info:
The network information of the given `instance`.
:param dict block_device_info:
Information about the block devices.
:param int timeout:
The time in seconds to wait for the guest OS to shutdown.
:param int retry_interval:
How often to signal guest while waiting for it to shutdown.
:return: A list of disk information dicts in JSON format.
:rtype: str
"""
if samehost:
reason = (_("'%s' branded zones do not currently support resize "
"to a different host.") % brand)
reason = (_("Unable to change brand of zone during resize."))
msg = (_("Unable to resize to a smaller boot volume."))
disk_info = None
break
else:
# If this is a non-global zone that is on the same host and is
# simply using a dataset, the disk size is purely an OpenStack
# quota. We can continue without doing any disk work.
return disk_info
else:
msg = (_("Cannot find an attached root device."))
else:
if volume_id is None:
msg = (_("Cannot find an attached root device."))
# creating a new volume, so we do likewise here.
while True:
break
try:
except Exception:
raise
return disk_info
"""Snapshots the specified instance.
:param context: security context
:param instance: nova.objects.instance.Instance
:param image_id: Reference to a pre-created image that will
hold the snapshot.
"""
if zone is None:
# look to see if the zone is a kernel zone and is powered off. If it
# is raise an exception before trying to archive it
# Get original base image info
try:
except exception.ImageNotFound:
base = {}
# Build updated snapshot image metadata
metadata = {
'is_public': False,
'status': 'active',
'properties': {
'image_location': 'snapshot',
'image_state': 'available',
}
}
# Match architecture, hypervisor_type and vm_mode properties to base
# image.
# Set generic container and disk formats initially in case the glance
# service rejects Unified Archives (uar) and ZFS in metadata.
try:
# Upload the archive image to the image service
try:
# Try to update the image metadata container and disk
# formats more suitably for a unified archive if the
# glance server recognises them.
"container and disk formats 'uar' and "
"'zfs'. Using generic values 'ovf' and "
"'raw' as fallbacks."))
finally:
# Delete the snapshot image file source
"""Cleans up any resources left after an interrupted snapshot.
:param context: security context
:param instance: nova.objects.instance.Instance
"""
pass
"""Best effort attempt at cleaning up any additional resources that are
not directly managed by Nova or Cinder so as not to leak these
resources.
"""
if disk_info:
if old_rvid:
if not samehost:
:param disk_info: the newly transferred disk information
:param network_info:
:py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
:param nova.objects.ImageMeta image_meta:
The metadata of the image of the instance.
:param resize_instance: True if the instance is being resized,
False otherwise
:param block_device_info: instance volume block device info
:param power_on: True if the instance should be powered on, False
otherwise
"""
if samehost:
if disk_info:
break
try:
if samehost:
# Add the new disk to the volume if the size of the disk
# changed
if disk_info:
root_ci['serial'],
else:
# No need to check disk_info here, because when not on the
# same host a disk_info is always passed in.
mount_dev = 'c1d0'
disk_info['id'],
0, mount_dev,
connection_info, None)
if zone is None:
if power_on:
if brand == ZONE_BRAND_SOLARIS:
return
# Toggle the autoexpand to extend the size of the rpool.
# We need to sleep for a few seconds to make sure the zone
# is in a state to accept the toggle. Once bugs are fixed
# around the autoexpand and the toggle is no longer needed
# or zone.boot() returns only after the zone is ready we
# can remove this hack.
'autoexpand=off', 'rpool')
'autoexpand=on', 'rpool')
except Exception:
# Attempt to cleanup the new zone and new volume to at least
# give the user a chance to recover without too many hoops
raise
:param instance: nova.objects.instance.Instance
"""
{'display_name': new_vname})
if not samehost:
else:
"""Handles the zone root volume switch-over or simply
initializing the connection for the new zone if not resizing to the
same host
:param context: the context for the _resize_disk_migration
:param instance: nova.objects.instance.Instance being resized
:param configured: id of the current configured volume
:param replacement: id of the new volume
:param newvolumesz: size of the new volume
:param mountdev: the mount point of the device
:param samehost: is the resize happening on the same host
"""
if samehost:
if zone is None:
# Need to detach the zone and re-attach the zone if this is a
# non-global zone so that the update of the rootzpool resource does
# not fail.
try:
finally:
try:
except Exception:
raise
try:
except Exception:
raise
if not samehost:
return connection_info
:param context: the context for the finish_revert_migration
:param network_info:
:py:meth:`~nova.network.manager.NetworkManager.get_instance_nw_info`
:param block_device_info: instance volume block device info
:param power_on: True if the instance should be powered on, False
otherwise
"""
# If this is not a samehost migration then we need to re-attach the
# original volume to the instance. Otherwise we need to update the
# original zone configuration.
if samehost:
if old_rvid:
else:
if new_rvid:
"""Pause the given instance.
A paused instance doesn't use CPU cycles of the host anymore. The
state of the VM could be stored in the memory or storage space of the
host, depending on the underlying hypervisor technology.
A "stronger" version of `pause` is :func:'suspend'.
The counter action for `pause` is :func:`unpause`.
:param nova.objects.instance.Instance instance:
The instance which should be paused.
:return: None
"""
# TODO(Vek): Need to pass context in for access to auth_token
raise NotImplementedError()
"""Unpause the given paused instance.
The paused instance gets unpaused and will use CPU cycles of the
host again. The counter action for 'unpause' is :func:`pause`.
Depending on the underlying hypervisor technology, the guest has the
same state as before the 'pause'.
:param nova.objects.instance.Instance instance:
The instance which should be unpaused.
:return: None
"""
# TODO(Vek): Need to pass context in for access to auth_token
raise NotImplementedError()
"""Suspend the specified instance.
A suspended instance doesn't use CPU cycles or memory of the host
anymore. The state of the instance could be persisted on the host
and allocate storage space this way. A "softer" way of `suspend`
is :func:`pause`. The counter action for `suspend` is :func:`resume`.
:param nova.context.RequestContext context:
The context for the suspend.
:param nova.objects.instance.Instance instance:
The instance to suspend.
:return: None
"""
if zone is None:
# Only Solaris kernel zones are currently supported.
reason = (_("'%s' branded zones do not currently support "
"suspend. Use 'nova reset-state --active %s' "
"to reset instance state back to 'active'.")
try:
'%{zonename}')
# add suspend if not configured
# replace the old suspend resource with the new one
"""resume the specified suspended instance.
The suspended instance gets resumed and will use CPU cycles and memory
of the host again. The counter action for 'resume' is :func:`suspend`.
Depending on the underlying hypervisor technology, the guest has the
same state as before the 'suspend'.
:param nova.context.RequestContext context:
The context for the resume.
:param nova.objects.instance.Instance instance:
The suspended instance to resume.
:param nova.network.model.NetworkInfo network_info:
Necessary network information for the resume.
:param dict block_device_info:
Instance volume block device info.
:return: None
"""
if zone is None:
# Only Solaris kernel zones are currently supported.
reason = (_("'%s' branded zones do not currently support "
# check that the instance is suspended
try:
block_device_info=None):
"""resume guest state when a host is booted.
:param instance: nova.objects.instance.Instance
"""
if zone is None:
# TODO(dcomay): Should reconcile with value of zone's autoboot
# property.
return
"""Rescue the specified instance.
:param nova.context.RequestContext context:
The context for the rescue.
:param nova.objects.instance.Instance instance:
The instance being rescued.
:param nova.network.model.NetworkInfo network_info:
Necessary network information for the resume.
:param nova.objects.ImageMeta image_meta:
The metadata of the image of the instance.
:param rescue_password: new root password to set for rescue.
"""
raise NotImplementedError()
:param instance: nova.objects.instance.Instance
"""
raise NotImplementedError()
"""Unrescue the specified instance.
:param instance: nova.objects.instance.Instance
"""
# TODO(Vek): Need to pass context in for access to auth_token
raise NotImplementedError()
"""Power off the specified instance.
:param instance: nova.objects.instance.Instance
:param timeout: time to wait for GuestOS to shutdown
:param retry_interval: How often to signal guest while
waiting for it to shutdown
"""
block_device_info=None):
"""Power on the specified instance.
:param instance: nova.objects.instance.Instance
"""
"""Trigger crash dump mechanism on the given instance.
Stalling instances can be triggered to dump the crash data. How the
guest OS reacts in details, depends on the configuration of it.
:param nova.objects.instance.Instance instance:
The instance where the crash dump should be triggered.
:return: None
"""
raise NotImplementedError()
"""Soft delete the specified instance.
A soft-deleted instance doesn't allocate any resources anymore, but is
still available as a database entry. The counter action :func:`restore`
uses the database entry to create a new instance based on that.
:param nova.objects.instance.Instance instance:
The instance to soft-delete.
:return: None
"""
raise NotImplementedError()
"""Restore the specified soft-deleted instance.
The restored instance will be automatically booted. The counter action
for `restore` is :func:`soft_delete`.
:param nova.objects.instance.Instance instance:
The soft-deleted instance which should be restored from the
soft-deleted data.
:return: None
"""
raise NotImplementedError()
"""Get the value of property from the zpool."""
try:
value = None
return value
return value
"""Update currently known host stats."""
host_stats = {}
if size is not None:
else:
# Account for any existing processor sets by looking at the the number
# of CPUs not assigned to any processor sets.
if data is not None:
else:
# Subtract the number of free pages from the total to get the used.
uri = "kstat:/pages/unix/system_pages"
if data is not None:
else:
if free is not None:
else:
free_disk_gb = 0
host_stats['hypervisor_version'] = \
else:
cpu_info = {
'arch': architecture
}
host_stats['supported_instances'] = [
]
host_stats['numa_topology'] = None
"""Retrieve resource information.
This method is called when nova-compute launches, and
as part of a periodic task that records the results in the DB.
:param nodename:
node which the caller want to get resources from
a driver that manages only one node can safely ignore this
:returns: Dictionary describing resources
"""
resources = {}
return resources
"""Prepare an instance for live migration
:param context: security context
:param instance: nova.objects.instance.Instance object
:param block_device_info: instance block device information
:param network_info: instance network information
:param disk_info: instance disk information
:param migrate_data: a LiveMigrateData object
"""
return migrate_data
"""Live migration of a Solaris kernel zone to another host."""
if zone is None:
options = []
if live_migration_cipher is not None:
if dry_run:
migrate_data=None):
"""Live migration of an instance to another host.
:param context: security context
:param instance:
nova.db.sqlalchemy.models.Instance object
instance object that is migrated.
:param dest: destination host
:param post_method:
post operation method.
expected nova.compute.manager._post_live_migration.
:param recover_method:
recovery method when any exception occurs.
expected nova.compute.manager._rollback_live_migration.
:param block_migration: if true, migrate VM disk.
:param migrate_data: a LiveMigrateData object
"""
try:
with excutils.save_and_reraise_exception():
"'%s' via zonemgr(3RAD): %s")
"""Force live migration to complete
:param instance: Instance being live migrated
"""
raise NotImplementedError()
"""Abort an in-progress live migration.
:param instance: instance that is live migrating
"""
raise NotImplementedError()
migrate_data=None):
"""Clean up destination node after a failed live migration.
:param context: security context
:param instance: instance object that was being migrated
:param network_info: instance network information
:param block_device_info: instance block device information
:param destroy_disks:
if true, destroy disks at destination during cleanup
:param migrate_data: a LiveMigrateData object
"""
pass
migrate_data=None):
"""Post operation of live migration at source host.
:param context: security context
:instance: instance object that was migrated
:block_device_info: instance block device information
:param migrate_data: a LiveMigrateData object
"""
try:
# These methods log if problems occur so no need to double log
# here. Just catch any stray exceptions and allow destroy to
# proceed.
except Exception:
pass
# If instance cannot be found, just return.
if zone is None:
% name)
return
try:
raise
"""Unplug VIFs from networks at source.
:param context: security context
:param instance: instance object reference
:param network_info: instance network information
"""
block_device_info=None):
"""Post operation of live migration at destination host.
:param context: security context
:param instance: instance object that is migrated
:param network_info: instance network information
:param block_migration: if true, post operation of block_migration.
"""
"""Check if instance files located on shared storage.
This runs check on the destination host, and then calls
back to the source host to check the results.
:param context: security context
:param instance: nova.objects.instance.Instance object
"""
raise NotImplementedError()
"""Check if instance files located on shared storage.
:param context: security context
:param data: result of check_instance_shared_storage_local
"""
raise NotImplementedError()
"""Do cleanup on host after check_instance_shared_storage calls
:param context: security context
:param data: result of check_instance_shared_storage_local
"""
pass
"""Check if it is possible to execute live migration.
This runs checks on the destination host, and then calls
back to the source host to check the results.
:param context: security context
:param instance: nova.db.sqlalchemy.models.Instance
:param src_compute_info: Info about the sending machine
:param dst_compute_info: Info about the receiving machine
:param block_migration: if true, prepare for block migration
:param disk_over_commit: if true, allow disk over commit
:returns: a LiveMigrateData object (hypervisor-dependent)
"""
if src_cpu_arch != dst_cpu_arch:
reason = (_("CPU architectures between source host '%s' (%s) and "
"destination host '%s' (%s) are incompatible.")
dst_compute_info['hypervisor_hostname'],
if brand != ZONE_BRAND_SOLARIS_KZ:
# Only Solaris kernel zones are currently supported.
reason = (_("'%s' branded zones do not currently support live "
"migration.") % brand)
if block_migration:
reason = (_('Block migration is not currently supported.'))
if disk_over_commit:
reason = (_('Disk overcommit is not currently supported.'))
dst_compute_info['hypervisor_hostname']
return dest_check_data
"""Do required cleanup on dest host after check_can_live_migrate calls
:param context: security context
:param dest_check_data: result of check_can_live_migrate_destination
"""
pass
"""Check if local volumes are attached to the instance."""
if driver_type == 'local':
reason = (_("Instances with attached '%s' volumes are not "
"currently supported.") % driver_type)
dest_check_data, block_device_info=None):
"""Check if it is possible to execute live migration.
This checks if the live migration can succeed, based on the
results from check_can_live_migrate_destination.
:param context: security context
:param instance: nova.db.sqlalchemy.models.Instance
:param dest_check_data: result of check_can_live_migrate_destination
:param block_device_info: result of _get_instance_block_device_info
:returns: a LiveMigrateData object
"""
try:
return dest_check_data
block_device_info=None):
"""Retrieve information about actual disk sizes of an instance.
:param instance: nova.objects.Instance
:param block_device_info:
Optional; Can be used to filter out devices which are
actually volumes.
:return:
json strings with below format::
"[{'path':'disk',
'type':'raw',
'virt_disk_size':'10737418240',
'backing_file':'backing_file',
'disk_size':'83886080'
'over_committed_disk_size':'10737418240'},
...]"
"""
raise NotImplementedError()
"""This method is called after a change to security groups.
All security groups and their associated rules live in the datastore,
and calling this method should apply the updated rules to instances
running the specified security group.
An error should be raised if the operation cannot complete.
"""
# TODO(Vek): Need to pass context in for access to auth_token
raise NotImplementedError()
"""Refresh security group rules
Gets called when an instance gets added to or removed from
the security group the instance is a member of or if the
group gains or loses a rule.
"""
raise NotImplementedError()
"""reset networking for specified instance."""
# TODO(Vek): Need to pass context in for access to auth_token
pass
"""Setting up filtering rules and waiting for its completion.
To migrate an instance, filtering rules to hypervisors
and firewalls are inevitable on destination host.
( Waiting only for filtering rules to hypervisor,
since filtering rules to firewall rules can be set faster).
Concretely, the below method must be called.
- setup_basic_filtering (for nova-basic, etc.)
- prepare_instance_filter(for nova-instance-instance-xxx, etc.)
to_xml may have to be called since it defines PROJNET, PROJMASK.
but libvirt migrates those value through migrateToURI(),
so , no need to be called.
Don't use thread for this method since migration should
not be started when setting-up filtering rules operations
are not completed.
:param instance: nova.objects.instance.Instance object
"""
# TODO(Vek): Need to pass context in for access to auth_token
pass
"""Defer application of IPTables rules."""
pass
"""Turn off deferral of IPTables rules and apply the rules now."""
pass
"""Stop filtering instance."""
# TODO(Vek): Need to pass context in for access to auth_token
pass
"""Set the root password on the specified instance.
:param instance: nova.objects.instance.Instance
:param new_pass: the new password
"""
if zone is None:
else:
"""Writes a file on the specified instance.
The first parameter is an instance of nova.compute.service.Instance,
and so the instance is being specified as instance.name. The second
parameter is the base64-encoded path to which the file is to be
written on the instance; the third is the contents of the file, also
base64-encoded.
NOTE(russellb) This method is deprecated and will be removed once it
can be removed from nova.compute.manager.
"""
# TODO(Vek): Need to pass context in for access to auth_token
raise NotImplementedError()
"""Applies a diff to the instance metadata.
This is an optional driver method which is used to publish
changes to the instance's metadata to the hypervisor. If the
hypervisor has no means of publishing the instance metadata to
the instance, then this method should not be implemented.
:param context: security context
:param instance: nova.objects.instance.Instance
"""
pass
"""inject network info for specified instance."""
# TODO(Vek): Need to pass context in for access to auth_token
pass
"""Perform a reboot on all given 'instances'.
Reboots the given `instances` which are longer in the rebooting state
than `timeout` seconds.
:param int timeout:
The timeout (in seconds) for considering rebooting instances
to be stuck.
:param list instances:
A list of nova.objects.instance.Instance objects that have been
in rebooting state longer than the configured timeout.
:return: None
"""
# TODO(Vek): Need to pass context in for access to auth_token
raise NotImplementedError()
"""Reboots, shuts down or powers up the host.
:param str action:
The action the host should perform. The valid actions are:
""startup", "shutdown" and "reboot".
:return: The result of the power action
:rtype: : str
"""
raise NotImplementedError()
On start, it triggers the migration of all instances to other hosts.
Consider the combination with :func:`set_host_enabled`.
:param str host:
The name of the host whose maintenance mode should be changed.
:param bool mode:
If `True`, go into maintenance mode. If `False`, leave the
maintenance mode.
:return: "on_maintenance" if switched to maintenance mode or
"off_maintenance" if maintenance mode got left.
:rtype: str
"""
raise NotImplementedError()
"""Sets the ability of this host to accept new instances.
:param bool enabled:
If this is `True`, the host will accept new instances. If it is
`False`, the host won't accept new instances.
:return: If the host can accept further instances, return "enabled",
if further instances shouldn't be scheduled to this host,
return "disabled".
:rtype: str
"""
# TODO(Vek): Need to pass context in for access to auth_token
raise NotImplementedError()
"""Returns the result of calling the Linux command `uptime` on this
host.
:return: A text which contains the uptime of this host since the
last boot.
:rtype: str
"""
# TODO(Vek): Need to pass context in for access to auth_token
"""Plug virtual interfaces (VIFs) into the given `instance` at
instance boot time.
The counter action is :func:`unplug_vifs`.
:param nova.objects.instance.Instance instance:
The instance which gets VIFs plugged.
:param nova.network.model.NetworkInfo network_info:
The object which contains information about the VIFs to plug.
:return: None
"""
# TODO(Vek): Need to pass context in for access to auth_token
pass
# NOTE(markus_z): 2015-08-18
# The compute manager doesn't use this interface, which seems odd
# since the manager should be the controlling thing here.
"""Unplug virtual interfaces (VIFs) from networks.
The counter action is :func:`plug_vifs`.
:param nova.objects.instance.Instance instance:
The instance which gets VIFs unplugged.
:param nova.network.model.NetworkInfo network_info:
The object which contains information about the VIFs to unplug.
:return: None
"""
raise NotImplementedError()
"""Get the currently known host CPU stats.
:returns: a dict containing the CPU stat info, eg:
| {'kernel': kern,
| 'idle': idle,
| 'user': user,
| 'iowait': wait,
| 'frequency': freq},
where kern and user indicate the cumulative CPU time
(nanoseconds) spent by kernel and user processes
respectively, idle indicates the cumulative idle CPU time
(nanoseconds), wait indicates the cumulative I/O wait CPU
time (nanoseconds), since the host is booting up; freq
indicates the current CPU frequency (MHz). All values are
long integers.
"""
raise NotImplementedError()
"""Return performance counters associated with the given disk_id on the
given instance. These are returned as [rd_req, rd_bytes, wr_req,
wr_bytes, errs], where rd indicates read, wr indicates write, req is
the total number of I/O requests made, bytes is the total number of
bytes transferred, and errs is the number of requests held up due to a
full pipeline.
All counters are long integers.
This method is optional. On some platforms (e.g. XenAPI) performance
statistics can be retrieved directly in aggregate form, without Nova
having to do the aggregation. On those platforms, this method is
unused.
Note that this function takes an instance ID.
"""
raise NotImplementedError()
"""Does the driver want networks deallocated on reschedule?"""
return False
"""What MAC addresses must this instance have?
Some hypervisors (such as bare metal) cannot do freeform virtualisation
of MAC addresses. This method allows drivers to return a set of MAC
addresses that the instance is to have. allocate_for_instance will take
this into consideration when provisioning networking for the instance.
Mapping of MAC addresses to actual networks (or permitting them to be
freeform) is up to the network implementation layer. For instance,
with openflow switches, fixed MAC addresses can still be virtualised
onto any L2 domain, with arbitrary VLANs etc, but regular switches
require pre-configured MAC->network mappings that will match the
actual configuration.
Most hypervisors can use the default implementation which returns None.
Hypervisors with MAC limits should return a set of MAC addresses, which
will be supplied to the allocate_for_instance call by the compute
manager, and it is up to that call to ensure that all assigned network
details are compatible with the set of MAC addresses.
This is called during spawn_instance by the compute manager.
:return: None, or a set of MAC ids (e.g. set(['12:34:56:78:90:ab'])).
None means 'no constraints', a set means 'these and only these
MAC addresses'.
"""
return None
"""Get DHCP options for this instance.
Some hypervisors (such as bare metal) require that instances boot from
the network, and manage their own TFTP service. This requires passing
the appropriate options out to the DHCP service. Most hypervisors can
use the default implementation which returns None.
This is called during spawn_instance by the compute manager.
Note that the format of the return value is specific to the Neutron
client API.
:return: None, or a set of DHCP options, eg:
| [{'opt_name': 'bootfile-name',
| {'opt_name': 'server-ip-address',
| 'opt_value': '1.2.3.4'},
| {'opt_name': 'tftp-server',
| 'opt_value': '1.2.3.4'}
| ]
"""
return None
"""Manage the driver's local image cache.
Some drivers chose to cache images for instances on disk. This method
is an opportunity to do management of that cache which isn't directly
related to other calls into the driver. The prime example is to clean
the cache and remove images which are no longer of interest.
:param all_instances: nova.objects.instance.InstanceList
"""
pass
"""Add a compute host to an aggregate.
The counter action to this is :func:`remove_from_aggregate`
:param nova.context.RequestContext context:
The security context.
:param nova.objects.aggregate.Aggregate aggregate:
The aggregate which should add the given `host`
:param str host:
The name of the host to add to the given `aggregate`.
:param dict kwargs:
A free-form thingy...
:return: None
"""
# NOTE(jogo) Currently only used for XenAPI-Pool
raise NotImplementedError()
"""Remove a compute host from an aggregate.
The counter action to this is :func:`add_to_aggregate`
:param nova.context.RequestContext context:
The security context.
:param nova.objects.aggregate.Aggregate aggregate:
The aggregate which should remove the given `host`
:param str host:
The name of the host to remove from the given `aggregate`.
:param dict kwargs:
A free-form thingy...
:return: None
"""
raise NotImplementedError()
"""Undo for Resource Pools."""
raise NotImplementedError()
"""Get connector information for the instance for attaching to volumes.
Connector information is a dictionary representing the ip of the
machine that will be making the connection, the name of the iscsi
initiator, the WWPN and WWNN values of the Fibre Channel initiator,
and the hostname of the machine as follows::
{
'ip': ip,
'initiator': initiator,
'wwnns': wwnns,
'wwpns': wwpns,
'host': hostname
}
"""
connector = {
}
if not self._initiator:
if self._initiator:
else:
'World Wide Node Names'),
'World Wide Port Names'),
return connector
"""Returns nodenames of all nodes managed by the compute service.
This method is for multi compute-nodes support. If a driver supports
multi compute-nodes, this method returns a list of nodenames managed
by the service. Otherwise, this method should return
[hypervisor_hostname].
"""
return [s['hypervisor_hostname'] for s in stats]
"""Return whether this compute service manages a particular node."""
return True
# Refresh and check again.
"""Get information about instance resource usage.
:returns: dict of nova uuid => dict of usage info
"""
return {}
"""Checks access of instance files on the host.
:param instance: nova.objects.instance.Instance to lookup
Returns True if files of an instance with the supplied ID accessible on
the host, False otherwise.
.. note::
Used in rebuild for HA implementation and required for validation
of access to instance shared disk files
"""
instance['uuid'])
root_ci = None
if entry['connection_info'] is None:
continue
break
if root_ci is None:
msg = (_("Unable to find the root device for instance '%s'.")
% instance['name'])
return driver_type in shared_storage
"""Register a callback to receive events.
Register a callback to receive asynchronous event
notifications from hypervisors. The callback will
be invoked with a single parameter, which will be
an instance of the nova.virt.event.Event class.
"""
"""Dispatches an event to the compute manager.
Invokes the event callback registered by the
compute manager to dispatch the event. This
must only be invoked from a green thread.
"""
if not self._compute_event_callback:
return
raise ValueError(
_("Event must be an instance of nova.virt.event.Event"))
try:
"""Delete any lingering instance files for an instance.
:param instance: nova.objects.instance.Instance
:returns: True if the instance was deleted from disk, False otherwise.
"""
# Delete the zone configuration for the instance using destroy, because
# it will simply take care of the work, and we don't need to duplicate
# the code here.
try:
except Exception:
return False
return True
"""Tell the caller if the driver requires legacy block device info.
Tell the caller whether we expect the legacy format of block
device info to be passed in to methods that expect it.
"""
return True
"""Snapshots volumes attached to a specified instance.
The counter action to this is :func:`volume_snapshot_delete`
:param nova.context.RequestContext context:
The security context.
:param nova.objects.instance.Instance instance:
The instance that has the volume attached
:param uuid volume_id:
Volume to be snapshotted
:param create_info: The data needed for nova to be able to attach
to the volume. This is the same data format returned by
Cinder's initialize_connection() API call. In the case of
doing a snapshot, it is the image file Cinder expects to be
used as the active disk after the snapshot operation has
completed. There may be other data included as well that is
needed for creating the snapshot.
"""
raise NotImplementedError()
"""Deletes a snapshot of a volume attached to a specified instance.
The counter action to this is :func:`volume_snapshot_create`
:param nova.context.RequestContext context:
The security context.
:param nova.objects.instance.Instance instance:
The instance that has the volume attached.
:param uuid volume_id:
Attached volume associated with the snapshot
:param uuid snapshot_id:
The snapshot to delete.
:param dict delete_info:
Volume backend technology specific data needed to be able to
complete the snapshot. For example, in the case of qcow2 backed
snapshots, this would include the file being merged, and the file
being merged into (if appropriate).
:return: None
"""
raise NotImplementedError()
"""Provide a default root device name for the driver.
:param nova.objects.instance.Instance instance:
The instance to get the root device for.
:param nova.objects.ImageMeta image_meta:
The metadata of the image of the instance.
:param nova.objects.BlockDeviceMapping root_bdm:
The description of the root device.
"""
raise NotImplementedError()
"""Default the missing device names in the block device mapping."""
raise NotImplementedError()
"""Get the next device name based on the block device mapping.
:param instance: nova.objects.instance.Instance that volume is
requesting a device name
:param bdms: a nova.objects.BlockDeviceMappingList for the instance
:param block_device_obj: A nova.objects.BlockDeviceMapping instance
with all info about the requested block
device. device_name does not need to be set,
and should be decided by the driver
implementation if not set.
:returns: The chosen device name.
"""
raise NotImplementedError()
"""Check whether the file format is supported by this driver
:param fs_type: the file system type to be checked,
the validate values are defined at disk API module.
"""
# NOTE(jichenjc): Return False here so that every hypervisor
# need to define their supported file system
# type and implement this function at their
# virt layer.
return False
"""Quiesce the specified instance to prepare for snapshots.
If the specified instance doesn't support quiescing,
InstanceQuiesceNotSupported is raised. When it fails to quiesce by
other errors (e.g. agent timeout), NovaException is raised.
:param context: request context
:param instance: nova.objects.instance.Instance to be quiesced
:param nova.objects.ImageMeta image_meta:
The metadata of the image of the instance.
"""
raise NotImplementedError()
"""Unquiesce the specified instance after snapshots.
If the specified instance doesn't support quiescing,
InstanceQuiesceNotSupported is raised. When it fails to quiesce by
other errors (e.g. agent timeout), NovaException is raised.
:param context: request context
:param instance: nova.objects.instance.Instance to be unquiesced
:param nova.objects.ImageMeta image_meta:
The metadata of the image of the instance.
"""
raise NotImplementedError()
"""Get host ID to associate with network ports.
:param context: request context
:param instance: nova.objects.instance.Instance that the network
ports will be associated with
:returns: a string representing the host ID
"""